Hey! Limiting number of characters is really easy if you have standard keyboard. The link below offers so many options for this prob:
http://stackoverflow.com/questions/7010547/uitextfield-text-change-event
But these options werent fit for me. In my case, I had custom keyboard…
The solution I found was pretty satisfying.
I wrote a function to check max length of a text field. Then I checked this func every time I added character to my textfield.
@IBAction func addBtnLabel(sender: AnyObject) { txtFieldPlateNumber.text = txtFieldPlateNumber.text?.stringByAppendingString(sender.titleLabel!!.text!) checkMaxLength(txtFieldPlateNumber as! UITextField, maxLength: 14) } func checkMaxLength(textField: UITextField!, maxLength: Int) { if (textField.text?.utf16.count > maxLength) { deleteLastCharacter() } } //To delete backwards. func deleteLastCharacter(){ if (txtFieldPlateNumber == 0) { // textField is empty print("text field is empty") } else{ var name: String = txtFieldPlateNumber.text! var truncated = String(name.characters.dropLast()) txtFieldPlateNumber.text = truncated } }
Thinking simple, creates simple solutions. 🙂