swift 2.3에서 Swift 3으로 코드를 변경했습니다. 다음 코드는 swift 2.3에서는 잘 작동하지만 swift 3에서는 효과가 없습니다.Swift 3 UITextView에서 선택한 텍스트의 색을 변경하십시오.
사용자 정의 텍스트 편집기를 개발하고 싶습니다. 그리고 사용자가 텍스트를 선택하고 색상을 변경하도록하십시오. 그 때문에이 코드를 사용하고 있습니다.
let selectedRange = textView.selectedRange
let currentAttr = textView.textStorage.attributes(at: selectedRange.location, effectiveRange: nil)
var attrName = NSForegroundColorAttributeName
if !isForeGround{
attrName = NSBackgroundColorAttributeName
}
if currentAttr[attrName] == nil || currentAttr[attrName] as! UIColor != selectedUIColor{
let dict = [attrName:selectedUIColor]
let currentFont = currentAttr[NSFontAttributeName]
let fontDescriptor = (currentFont! as AnyObject).fontDescriptor
let updatedFont = UIFont(descriptor: fontDescriptor!, size: 0.0)
let dict2 = [NSFontAttributeName: updatedFont]
textView.textStorage.beginEditing()
if currentAttr.count>0{
textView.textStorage.addAttributes(dict, range: selectedRange)
}else{
textView.textStorage.setAttributes(dict, range: selectedRange)
}
textView.textStorage.addAttributes(dict2, range: selectedRange)
textView.textStorage.endEditing()
}
성공적으로 실행되지만 텍스트 색상에는 영향을주지 않습니다.