限制iPhone UITextField上的字符输入

时间:2012-04-03 05:41:10

标签: iphone objective-c

  

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

有没有办法只让用户通过键盘输入字母和数字,没有符号到UITextField?

3 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:2)

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {    
  //return yes or no after comparing the characters
}

答案 2 :(得分:2)

试试这个:

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

}