Format UITextField text without having cursor move to the end

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

    To complement the other correct answers in this thread here are some code snippets for Swift 4.2 and for both UITextField and UITextView

    UITextField

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // Update Cursor
        let positionOriginal = textField.beginningOfDocument
        let cursorLocation = textField.position(from: positionOriginal, offset: (range.location + string.count))
        if let cursorLocation = cursorLocation {
            textField.selectedTextRange = textField.textRange(from: cursorLocation, to: cursorLocation)
        }
        return false
    }
    

    UITextView

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // Update Cursor
        let positionOriginal = textView.beginningOfDocument
        let cursorLocation = textView.position(from: positionOriginal, offset: (range.location + text.count))
        if let cursorLocation = cursorLocation {
            textView.selectedTextRange = textView.textRange(from: cursorLocation, to: cursorLocation)
        }
        return false
    }
    

提交回复
热议问题