Life needs limits. Whether its for usability reasons or maybe we're building the next Twitter, eventually we'll need to enforce a limit on how much content a user can enter into a UITextView. Let's take a look at how to do this.

let CharacterLimit = 182

class ViewController: UIViewController, UITextViewDelegate {
  let textView = UITextView(frame: CGRect.zero)

  override func viewDidLoad() {
    super.viewDidLoad()
    textView.delegate = self
  }

  func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    let currentText = textView.text as NSString
    let updatedText = currentText.stringByReplacingCharactersInRange(range, withString: text)

    return updatedText.characters.count <= CharacterLimit
  }
}

We'll start by defining our limit as a global variable, making it easy to change later.

Next, we'll add a new UITextView to our view controller, and set ourselves as its delegate. (The text view's layout is handled off camera).

Finally, in the shouldChangeTextInRange delegate function, we'll perform our checks.

We'll apply the proposed changes, and check if the resulting length is within our limits. The Bool we return describes if the change should be allowed.

And, we're done!

Update: March 28th, 6:15 PM

A previous version of this Bite contained an inferior implementation of the shouldChangeTextInRange: function. The one shown here comes from reader Filip Radelic. Thanks Filip!