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:
- Create a subclass of the
NSTextFieldbase class and name itCustomTextField. - Set the text field’s custom class attribute to
CustomTextFieldin Interface Builder. - Override the inherited
textDidChange(_:)instance method from theNSTextFieldsuperclass in yourCustomTextFieldderived 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:
https://developer.apple.com/documentation/appkit/nstextfield/1399397-textdidchange
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:
- Create a private
Int?property to store the text field’s digit. - 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
digitproperty in this case to either benilif the text field is actually still empty or the digit’s value if the text field contains only one digit. - 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
stringValueproperty in this case to either be the previous digit’s value or an emptyStringifdigitisnil.
You can read even more about the stringValue instance property over here:
https://developer.apple.com/documentation/appkit/nscontrol/1428950-stringvalue
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.