2017-04-25 4 views
0

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() 
     } 

성공적으로 실행되지만 텍스트 색상에는 영향을주지 않습니다.

답변

0

이것은 나를 위해 일했습니다.

let myAttribute = [ NSForegroundColorAttributeName: selectedUIColor]

그리고 마지막으로 :

textView.textStorage.addAttributes(myAttribute, range: selectedText)

그런 let selectedText = textView.selectedRange

, 당신은 속성을 작성 :

먼저 당신과 함께, 선택한 텍스트를 잡을 필요

이것은 발신자가 호출하는 작업에 있어야합니다.

희망 사항은 당신을 위해서도 좋습니다! 감사합니다.

관련 문제