2017-05-11 5 views
1

私は属性付き文字列でSwiftで作業しています。私の質問は、UITextFieldの属性付きテキストに属性付きの文字列を追加し、以前の色と属性をすべて保持する方法です。新しい属性付き文字列を追加すると、UITextFieldの前のテキストはすべて黒になり、その必要はありません。前回の色付き部分を残しておきたいのです。これまでのコードです:属性付き文字列をUITextFieldの属性付きテキストに追加し、以前の色と属性をすべて保持します。

var newMutableString = NSMutableAttributedString() 

if let completionTextHolderText = completionTextHolderText { 
    newMutableString = userTextField.attributedText?.mutableCopy() as! NSMutableAttributedString 
    let choosenSuggestion = createAttributed(string: completionTextHolderText, with: .blue) 
    newMutableString.append(choosenSuggestion) 

    let emptySpace = createAttributed(string: " ", with: .black) 
    newMutableString.append(emptySpace) 
} 

userTextField.attributedText = newMutableString.copy() as? NSAttributedString 

//------- 
    private func createAttributed(string: String, with color: UIColor) -> NSMutableAttributedString { 
      let attributedString = NSMutableAttributedString(string: string, attributes: [:]) 
      attributedString.addAttribute(NSForegroundColorAttributeName, 
             value: color, 
             range: NSRange(location: 0, length: string.characters.count)) 
      return attributedString 
    } 

ありがとうございます。

+0

。しかし、このコードがstatrtsで、createAttributed()メソッドが実行するとき、userTextField.attributedTextの属性にはどのような属性がありますか? –

+0

@AlexShubin - 私は自分の質問を編集し、 'createAttributed()'関数を追加しました。 'userTextField.attributedText'は青または黒のテキストを含んでいます。属性は 'NSForegroundColorAttributeName'だけです。たとえば、黒色の単語、黒色の単語、青色の単語、黒色の単語、青色の単語...など。順序は重要ではありません。 –

+0

私はあなたのコードが今働いている。あなたのメインセクションの後に何かが起こり、範囲の属性色がリセットされると思います。メインセクション –

答えて

0

私はあなたのコードが今働いています。私はあなたのメインセクションの前後に何か起こると思うし、範囲の属性の色をリセットします。

そして相続人は、あなたがそれをリファクタリングする方法のいくつかのアイデア:それは動作するはずの簡単な方法で

@IBAction func buttonClick(_ sender: UIButton) { 

    if let completionTextHolderText = completionTextHolderText, 
     let attrStr = userTextField.attributedText { 

     let newMutableString = attrStr.mutableCopy() as! NSMutableAttributedString 

     newMutableString.append(
      createAttributed(string: completionTextHolderText+" ", with: .blue) 
     ) 

     userTextField.attributedText = newMutableString 
    } 
} 

private func createAttributed(string: String, with color: UIColor) -> NSAttributedString { 
    return NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName : color]) 
} 
+1

はい、このコードの前に、私はUITextFieldのテキストを変更しています。そしてそれは問題でした。 –

関連する問題