Tip: Adding Fields To Interface Builder

Here’s a neat trick that might have never occurred to you — it didn’t to us, anyways:

How to use Xcode to set a text field’s maximum length, Visual Studio-style

There’s the [Visual Studio] GUI builder way…

  1. Select the text box.
  2. 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?

Alex | May 23, 2016
  • Daniel May 29, 2016 at 2:34 pm
    I think this means that you will retain any text field with a maximum length forever. I.e. this code is leaking memory. Consider using e.g. NSMapTable with weak keys or Objective-C associated objects (not easily accessible from Swift, though) instead.
  • richardmsmith January 10, 2019 at 10:04 pm
    Thanks for sharing information I must say very informative blog post. Keep it up!!

Leave a Reply