2017-04-25 9 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

、あなたが属性を作成します。

まずあなたが、あなたの選択したテキストをキャッチする必要があります

これは送信者から呼び出されたアクションに含まれている必要があります

うまく動作します。 よろしくお願いいたします。

関連する問題