I set UITextField.UIKeyboardType
is Number, but user can use other company's Keyboard;
user can tap "返回
"button, and the keyboard changed KeyboardType. KeyboardTypeChanged
I want force pop system number keyboard.
SystemNumberKeyboard
Asked
Active
Viewed 284 times
0

Suraj Sukale
- 1,778
- 1
- 12
- 19

user5814049
- 11
- 3
2 Answers
1
You can use UITextField delegate for restricting only number input:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let numbersOnly = NSCharacterSet(charactersInString:"0123456789").invertedSet
let compSepByCharInSet = string.componentsSeparatedByCharactersInSet(numbersOnly)
let numberFiltered = compSepByCharInSet.joinWithSeparator("")
return string == numberFiltered
}

MCMatan
- 8,623
- 6
- 46
- 85
-
Does this take into account that user might have copied text from somewhere tried to paste it into the textfield which is meant to only take numbers as input? – Yash Tamakuwala Aug 09 '16 at 14:39
-
Yes, try it your self (: – MCMatan Aug 09 '16 at 15:15
-
@user5814049 did it work for you? – MCMatan Aug 19 '16 at 12:13
-
I hadn't tried it. But now that I did, I couldn't make it work. – Yash Tamakuwala Aug 19 '16 at 13:07
-
Did you set the view/viewController with "shouldChangeCharactersInRange" function as the delegate of the TextFiled? – MCMatan Aug 19 '16 at 13:14
-
I did - class ViewController: UIViewController, UITextFieldDelegate. and copy pasted the above function. Did I miss something? – Yash Tamakuwala Aug 19 '16 at 13:21
-
@YashTamakuwala You should still set the delegate as your view, by "self.textField.delegate = self" – MCMatan Aug 19 '16 at 13:22
-
@YashTamakuwala If it works, please accept my answer. – MCMatan Aug 19 '16 at 14:38
0
In Objective-C you can do it like this by implementing UITextfield delegate method. Textfield will only allows number to be entered.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *CS = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *filtered=[[string componentsSeparatedByCharactersInSet:CS] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}

Mohd Khalil Ur Rehman
- 151
- 1
- 3