-
Re: text field numbers only
toshb Nov 2, 2016 8:06 PM (in response to ShinehahGnolaum)click on the text field and change the keyboard type from the right panel
-
Re: text field numbers only
Beast Nov 4, 2016 11:03 AM (in response to toshb)This proposed solution doesn't address paste nor an external keyboard.
-
-
Re: text field numbers only
Claude31 Nov 3, 2016 12:40 AM (in response to ShinehahGnolaum)You can also use controlTextDidChange
override func controlTextDidChange(obj: NSNotification) {
let object = obj.object as! NSTextField
if object !== cellTextField { return } /
someCellTextFieldHasChanged = true /
let lastChar = object.stringValue.count - 1 /
guard let typed = object.stringValue.lastChar else { return } /
if !"0123456789".containsChar(typed) {
cellTextField!.stringValue = cellTextField!.stringValue[0..<lastChar]
}
}
-
Re: text field numbers only
eskimo Nov 3, 2016 1:04 AM (in response to ShinehahGnolaum)ShinehahGnolaum wrote:
How do I force the user to enter only numbers in a text field?
What platform are you working on? So far you’ve got one iOS answer and one macOS answer!
Can you be more precise about what you mean by “numbers”. Are you looking to filter out everything that’s not a digit? Or do you want to handle things like decimal points? And do you want to force the user to use Western Arabic digits? Or will you accept other digits (for example, Eastern Arabic digits)?
toshb wrote:
click on the text field and change the keyboard type from the right panel
This is a good idea but be aware that it doesn’t prevent the user from entering text via other means (most notably, via Paste). You can catch other modifications via the
-shouldChangeTextInRange:replacementText:
callback.Also, if you want to force Western Arabic digits you’ll want to use ASCII Capable Number Pad (
UIKeyboardTypeASCIICapableNumberPad
) rather than Number Pad (UIKeyboardTypeNumberPad
).Claude31 wrote:
if !"0123456789".containsChar(typed) { cellTextField!.stringValue = cellTextField!.stringValue[0..<lastChar] }
Two things:
This assumes the user is using Western Arabic digits.
On macOS, you may be better off attaching a number formatter to your text field. You can set that up in IB or via the
formatter
of the text field cell.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardwarelet myEmail = "eskimo" + "1" + "@apple.com"
-
Re: text field numbers only
Beast Nov 4, 2016 11:07 AM (in response to ShinehahGnolaum)In the case of UITextField, you would want to implement the textField(_:shouldChangeCharactersIn:replacementString:) delegate, then filter out the characters you don't want in the input.
If you only want decimal characters, you could use NSCharacterSet's decimalDigits and filter out characters not present in that set.