【问题标题】:UITextField - Allow only numbers and punctuation input/keypadUITextField - 只允许数字和标点输入/键盘
【发布时间】:2013-12-06 00:15:28
【问题描述】:

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

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

}

感谢您的帮助。

【问题讨论】:

  • 将您的文本字段设置为:[textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
  • @Mutawe 这不会阻止用户更改为ABC 键盘。

标签: ios numbers iphone-keypad


【解决方案1】:

试试这个

制作宏

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

【讨论】:

  • 谢谢,textFieldAmount 是什么?
  • 我有多个文本字段,我正在检查。
【解决方案2】:

在 Swift 3 中:

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

【讨论】:

  • @SPatel 问题也是“只允许标点符号和数字”。 . 是标点符号
【解决方案3】:

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

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

因为在 iPad 上设置键盘类型没什么用...

【讨论】:

    【解决方案4】:

    随便用

    [textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
    

    创建文本字段后。

    【讨论】:

    • 这不会阻止用户更改为ABC 键盘。
    • @Gman 好吧,我想没有标准键盘可以完全满足您的要求...我想您必须为此目的制作自己的输入视图,尽管这对我来说似乎有点矫枉过正。
    • 它也不能防止将不正确的数据粘贴到文本字段中
    猜你喜欢
    • 2012-10-08
    • 2014-04-11
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    相关资源
    最近更新 更多