Format UITextField text without having cursor move to the end

后端 未结 6 1535
借酒劲吻你
借酒劲吻你 2020-12-23 17:21

I am trying to apply NSAttributedString styles to a UITextField after processing a new text entry, keystroke by keystroke. The problem is t

6条回答
  •  盖世英雄少女心
    2020-12-23 17:42

    This is an old question, but I had a similar issue and resolved it with the following Swift:

    // store the current cursor position as a range
    var preAttributedRange: NSRange = textField.selectedRange 
    // apply attributed string
    var attributedString:NSMutableAttributedString = NSMutableAttributedString(string: fullString)
    attributedString = format(textField.text) as NSMutableAttributedString
    textField.attributedText = attributedString
    // reapply the range
    textField.selectedRange = preAttributedRange
    

    It works in the context of my app, hopefully it's useful for someone!

提交回复
热议问题