The format of UITextField is changed after clearing the text and inputting new text.

I have a UITextField and set its text format(font/color/underline) by UITextField.attributedText. However, when I clear the text than input text again, the format is changed. It seems the behavior of attributedText is reset by system after clearing the text. Is this a bug or can we have some workaround to keep the consistent format after clearing the text? The code snippet is like below:

    let textField = UITextField(frame: CGRectMake(0, 0, 200, 60))
    let fontColor = .red
    let attrText = NSMutableAttributedString(string: "normal text")
    let range = NSRange(location: 0, length: attrText.length)
    attrText.addAttribute(.font, value: UIFont.systemFont(ofSize: 14), range: range)
    attrText.addAttribute(.foregroundColor, value: fontColor, range: range)
    attrText.addAttribute(.underlineColor, value: fontColor, range: range)
    attrText.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
    textField.attributedText = attrText
Answered by Frameworks Engineer in 774567022

Use UITextField.defaultAttributes to tell UITextField what attributes to use when there is no text.

Accepted Answer

Use UITextField.defaultAttributes to tell UITextField what attributes to use when there is no text.

The format of UITextField is changed after clearing the text and inputting new text.
 
 
Q