简体   繁体   中英

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

I'm working in Swift with attributed strings. My question is how to append attributed string to attributed text of UITextField and keep all it's previous colors and attributes. When I append new attributed string all previous text in UITextField becomes black and I don't want that, I want to keep it's previous colored parts. This Is the code so far:

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
    }

Thanks for your help.

I've got your code working now. I think something happens before or after your main section and resets attribute color for range.

And heres some idea of how you can refactor it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM