将属性字符串附加到 UITextField 的属性文本并保留其所有以前的颜色和属性

Append attributed string to attributed text of UITextField and keep all it's previous colors and attributes

我正在 Swift 使用属性字符串。我的问题是如何将属性字符串附加到 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
    }

感谢您的帮助。

你的代码现在可以正常工作了。我认为在您的主要部分之前或之后发生了一些事情,并重置了范围的属性颜色。

下面是关于如何重构它的一些想法:

@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])
}