UITextField - 仅允许数字和标点输入/键盘

时间:2013-11-21 13:35:42

标签: ios numbers iphone-keypad

我已尝试过下面的代码,但只允许输入键盘上的数字。我的应用程序要求键盘使用句点/句号(用于金钱交易)。我试过的代码是:

- (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;

}

感谢您的帮助。

4 个答案:

答案 0 :(得分:43)

试试这个

制作宏

#define ACCEPTABLE_CHARACTERS @"0123456789."

并使用它

- (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;
}

答案 1 :(得分:2)

只需使用

[textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];

创建文本域后。

答案 2 :(得分:2)

自定义字符集怎么样?像这样:

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

因为在iPad上设置键盘类型非常无用......

答案 3 :(得分:2)

在Swift 3中:

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