【问题标题】:Restricting character input on iPhone UITextField [duplicate]限制iPhone UITextField上的字符输入[重复]
【发布时间】:2012-04-03 05:41:10
【问题描述】:

可能重复:
allow only alphanumeric characters for a UITextField

有没有办法只让用户通过键盘在 UITextField 中输入字母和数字,而不是符号?

【问题讨论】:

  • Daidai,将您的 UITextField 键盘类型更改为“Name Phone Pad”。它只会显示要输入的字符或数字。
  • @H e m a n g - 感谢它的工作,但用户体验不正常。

标签: iphone objective-c


【解决方案1】:

使用这个委托方法..因为它对我有用..

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField == YOUR TEXT FIELD)
    {
        NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    else
        return YES;
}

【讨论】:

    【解决方案2】:
    - (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {    
      //return yes or no after comparing the characters
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
       {
         NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
              if(![string stringByTrimmingCharactersInSet:nonNumberSet].length)
              {
                  return NO;
              }
         return YES;
      

      }

      【讨论】:

      • 这只适用于小数,不是吗?
      • 是的,这段代码确保用户没有输入任何符号以及任何字符。您可以通过添加'||'根据您的要求进行修改int if 语句并比较字符。
      • 看起来你可以使用 NSCharacterSet alphanumericCharacterSet
      • 此代码禁用了 uitextview 的退格触摸(至少对于我的应用程序)。更好的解决方案是在 if 语句中使用 [string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 2015-01-28
      相关资源
      最近更新 更多