UITextField - 只允许数字和标点输入/键盘 [英] UITextField - Allow only numbers and punctuation input/keypad

查看:25
本文介绍了UITextField - 只允许数字和标点输入/键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

}

感谢您的帮助.

推荐答案

试试这个

制作宏

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

这篇关于UITextField - 只允许数字和标点输入/键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆