Format UITextField text without having cursor move to the end

后端 未结 6 1545
借酒劲吻你
借酒劲吻你 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 a code working for swift 2. Enjoy it!

     func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let beginnig: UITextPosition =  textField.beginningOfDocument
    
        if let txt = textField.text {
            textField.text = NSString(string: txt).stringByReplacingCharactersInRange(range, withString: string)
        }
    
        if let cursorLocation: UITextPosition = textField.positionFromPosition(beginnig, offset: (range.location + string.characters.count) ) {
            textField.selectedTextRange = textField.textRangeFromPosition(cursorLocation, toPosition: cursorLocation)
        }
    
        return false
    }
    

    Note that last "if let" should always stay at the end of code.

提交回复
热议问题