UITextField - Allow only numbers and punctuation input/keypad

主宰稳场 提交于 2019-11-29 09:29:45

问题


I have tried the code below but that only allows for numbers on the keypad to be inputted. My app requires the keypad to use a period/full stop (for money transactions). The code I tried is:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

   NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

     if ([string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound)
      {
         return NO;
    }
   return YES;

}

Thanks for any help.


回答1:


Try this

Make a macro

#define ACCEPTABLE_CHARACTERS @"0123456789."

And use it

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

    if (textField==textFieldAmount)
    {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return [string isEqualToString:filtered];
    }
    return YES;
}



回答2:


Just use

[textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];

after creating your textfield.




回答3:


How about a custom character set? Something like this:

NSCharacterSet *testChars = [NSCharacterSet characterSetWithCharactersInString:@"0123456789+*#-() "];

Because setting the keyboard type is pretty useless on iPad...




回答4:


In Swift 3:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = "0123456789!@#$%^&*()_+~:{}|\"?><\\`,./;'[]=-"
    return allowedCharacters.contains(string) || range.length == 1
}


来源:https://stackoverflow.com/questions/20122455/uitextfield-allow-only-numbers-and-punctuation-input-keypad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!