How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?
How can I set the maximum amount of characters in a UITextField on the
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
While the
UITextFieldclass has no max length property, it’s relatively simple to get this functionality by setting the text field’sdelegateand implementing the following delegate method:Objective-C
Swift
Before the text field changes, the UITextField asks the delegate if the specified text should be changed. The text field has not changed at this point, so we grab it’s current length and the string length we’re inserting (either through pasting copied text or typing a single character using the keyboard), minus the range length. If this value is too long (more than 25 characters in this example), return
NOto prohibit the change.When typing in a single character at the end of a text field, the
range.locationwill be the current field’s length, andrange.lengthwill be 0 because we’re not replacing/deleting anything. Inserting into the middle of a text field just means a differentrange.location, and pasting multiple characters just meansstringhas more than one character in it.Deleting single characters or cutting multiple characters is specified by a
rangewith a non-zero length, and an empty string. Replacement is just a range deletion with a non-empty string.A note on the crashing "undo" bug
As is mentioned in the comments, there is a bug with
UITextFieldthat can lead to a crash.If you paste in to the field, but the paste is prevented by your validation implementation, the paste operation is still recorded in the application’s undo buffer. If you then fire an undo (by shaking the device and confirming an Undo), the
UITextFieldwill attempt to replace the string it thinks it pasted in to itself with an empty string. This will crash because it never actually pasted the string in to itself. It will try to replace a part of the string that doesn’t exist.Fortunately you can protect the
UITextFieldfrom killing itself like this. You just need to ensure that the range it proposes to replace does exist within its current string. This is what the initial sanity check above does.swift 3.0 with copy and paste working fine.
Hope it’s helpful to you.