Tip: Adding Fields to Interface Builder

DZone 's Guide to

Tip: Adding Fields to Interface Builder

Check out this trick to allow Xcode to set a text field's max length, Visual Studio styles!

· Mobile Zone ·
Free Resource

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:

  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:

import UIKit
// 1
private var maxLengths = [UITextField: Int]()
// 2
extension UITextField {
  // 3
  @IBInspectable var maxLength: Int {
    get {
      // 4
      guard let length = maxLengths[self] else {
        return Int.max
      return length
    set {
      maxLengths[self] = newValue
      // 5
        action: #selector(limitLength),
        forControlEvents: UIControlEvents.EditingChanged
  func limitLength(textField: UITextField) {
    // 6
    guard let prospectiveText = textField.text
      where prospectiveText.characters.count > maxLength else {
    let selection = selectedTextRange
    // 7
    text = prospectiveText.substringWithRange(
      Range<String.Index>(prospectiveText.startIndex ..< prospectiveText.startIndex.advancedBy(maxLength))
    selectedTextRange = selection

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?

extensions ,field ,builder ,gui ,swift ,trick ,mobile ,mobile development ,xcode ,interface

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}