2014-02-19 52 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; 
} 
相關問題