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