I am trying to apply NSAttributedString styles to a UITextField after processing a new text entry, keystroke by keystroke. The problem is t
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
}