2014-02-19 18 views
-1

在我的iOS应用程序中,我有一个UITextField,它目前将其字符条目限制为50个字符,并且在收到单个字符时启用UIButton。我现在要做的是确保用户只能输入字母数字字符,但这是我遇到问题的地方。这里是我迄今为止代码:无法将字符限制为iOS中的UITextField中的字母数字

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

BOOL canEdit=NO; 
    NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet]; 
    NSUInteger newLength = [textField.text length] + [string length] - range.length; 

    if (newLength > 0) { 

     for (int i = 0; i < [string length]; i++) 
     { 
      unichar c = [string characterAtIndex:i]; 
      if (![myCharSet characterIsMember:c]) 
      { 
       canEdit=NO; 
       self.myButton.enabled = NO; 
      } 
      else 
      { 
       canEdit=YES; 
       self.myButton.enabled = YES; 
      } 
     } 

    } else self.myButton.enabled = NO; 


    return (newLength > 50 && canEdit) ? NO : YES; 
} 

本来,我的代码只是限制字符输入到仅有50个字符,使我的按钮看起来像下面这样:

NSUInteger newLength = [textField.text length] + [string length] - range.length; 

    if (newLength > 0) self.doneButton.enabled = YES; 
    else self.doneButton.enabled = NO; 

    return (newLength > 45) ? NO : YES; 

点我想说的是,我想在我现有的代码中加入字母数字字符的限制,而不是替换它。这对我来说是具有挑战性的部分。

+1

希望这将有助于you..http://rajneesh071.blogspot.in/2012/12/how-to-restrict-user-to-enter- character.html – Rajneesh071

+0

你已经[问这个,并得到了答案](http://stackoverflow.com/questions/21864312/need-to-limit-characters-to-only-alphanumeric-in-existing-uitextfield-in- ios),然后删除你的问题。不要转贴。 –

回答

1

当字符是非字母数字字符时,您需要循环并返回NO。所以,你有代码应该是这样的:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

    BOOL canEdit=NO; 
    NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet]; 
    for (int i = 0; i < [string length]; i++) { 
     unichar c = [string characterAtIndex:i]; 
     if (![myCharSet characterIsMember:c]) { 
      return NO; 
     } 
    } 
    NSUInteger newLength = [textField.text length] + [string length] - range.length; 

    if (newLength > 0) { 

     for (int i = 0; i < [string length]; i++) 
     { 
      unichar c = [string characterAtIndex:i]; 
      if (![myCharSet characterIsMember:c]) 
      { 
       canEdit=NO; 
       self.myButton.enabled = NO; 
      } 
      else 
      { 
       canEdit=YES; 
       self.myButton.enabled = YES; 
      } 
     } 

    } else self.myButton.enabled = NO; 


    return (newLength > 50 && canEdit) ? NO : YES; 
} 
相关问题