Search code examples
iosswiftnsattributedstring

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.


Solution

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