Format UITextField text without having cursor move to the end

后端 未结 6 1546
借酒劲吻你
借酒劲吻你 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:47

    Thanks @Stonz2 by the code in Objective-C. It works like a charm! I used it in my Swift project. The same code in Swift:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
        let positionOriginal = textField.beginningOfDocument
        let cursorLocation = textField.position(from: positionOriginal, offset: (range.location + NSString(string: string).length))
    
        /* MAKE YOUR CHANGES TO THE FIELD CONTENTS AS NEEDED HERE */
    
        if let cursorLoc = cursorLocation {
            textField.selectedTextRange = textField.textRange(from: cursorLoc, to: cursorLoc)
        }
        return false 
    }
    

提交回复
热议问题