Make NSTextField accept only digits

Hello, everyone. I am creating app for macOS. In this app, I have NSTextField. Currently, it can accept any symbols from the keyboard. How can I make NSTextField accept only digits?

@dafk This is quite a tricky one to get right because NSTextField on macOS behaves differently than UITextField on iOS. Here is what you need to do step by step in this case:

  1. Create a subclass of the NSTextField base class and name it CustomTextField.
  2. Set the text field’s custom class attribute to CustomTextField in Interface Builder.
  3. Override the inherited textDidChange(_:) instance method from the NSTextField superclass in your CustomTextField derived class. This method gets called automatically by the compiler each and every time the text in the text field changes.

You can read even more about the textDidChange(_:) method over here:

This is how your CustomTextField class implementation looks like in this case:

import Cocoa

class CustomTextField: NSTextField {
  // 1
  private var digit: Int?

  override func textDidChange(_ notification: Notification) {
    // 2
    if stringValue.isEmpty || (stringValue.count == 1 && Int(stringValue) != nil) {
      digit = Int(stringValue)
    // 3
    } else {
      stringValue = digit != nil ? String(digit!) : ""

There is quite a lot going on in the above block of code, so breaking it into steps:

  1. Create a private Int? property to store the text field’s digit.
  2. There are only two valid cases when the text field’s value doesn’t have to change no matter what. You go ahead and set the digit property in this case to either be nil if the text field is actually still empty or the digit’s value if the text field contains only one digit.
  3. The text field’s value is invalid in all other cases so you should definitely update its corresponding text to a valid state because of that. You go ahead and set the stringValue property in this case to either be the previous digit’s value or an empty String if digit is nil.

You can read even more about the stringValue instance property over here:

Please let me know if you have any questions or issues about the whole thing when you get a chance. Thank you!

This topic was automatically closed after 166 days. New replies are no longer allowed.