Here’s a neat trick that might have never occurred to you — it didn’t to us, anyways:
There’s the [Visual Studio] GUI builder way…
- Select the text box.
- Set its MaxLength property in the Properties pane.
… when developing Objective-C and Swift applications in Xcode:
There isn’t a GUI builder way — just a code way, and it’s a little more work than it needs to be…
… That’s a lot of work. Isn’t there a way we can get a “max length” property for text fields, like the .NET people?
And why, yes. Yes, there is! The trick is simply to create an @IBInspectable extension on UITextField:
Swift extensions let you add new functionality to existing classes, structs, enumerations, and protocols. We’re using an extension to UITextField to add two things:
maxLength, a property that lets the programmer set and get the maximum length of a text field, and
limitLength, a method called whenever the contents of a text field are changed, and limits the number of characters in that text field.
Look over the rest of the article and download the sample project for an explanation of the techniques used here. Mighty handy for extending built-in types if you like doing your interface work graphically in Interface Builder … and who doesn’t?