开发者

How to limit the amount of characters in 5 UITextFields [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

iPhone SDK: Set Max Character length TextField

I have 5 UITextFields, where only 6 characters should be allowed. How can I limit the input to just 6 characters per text field? Any other code I tried failed and I didn't found a way of fixing it, thanks :D EDIT: This is the codes I tested:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger newLength1 = [serie1.text length] + [string length] - range.length;
    NSUInteger newLength2 = [serie2.text length] + [string length] - range.length;
    NSUInteger newLe开发者_如何学Gongth3 = [serie3.text length] + [string length] - range.length;
    NSUInteger newLength4 = [serie4.text length] + [string length] - range.length;
    NSUInteger newLength5 = [serie5.text length] + [string length] - range.length;

    if(newLength1 > 6)
        return NO;
    if(newLength2 > 6)
        return NO; 
    if(newLength3 > 6)
        return NO; 
    if(newLength4 > 6)
        return NO; 
    if(newLength5 > 6)
        return NO;

    return YES;
}

and

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(serie1.text.length >= 6 && range.length == 0) {
        return NO;

    }
    if(serie2.text.length >= 6 && range.length == 0) {
        return NO;

    }
    if(serie3.text.length >= 6 && range.length == 0) {
        return NO;

    }
    if(serie4.text.length >= 6 && range.length == 0) {
        return NO;

    }
    if(serie5.text.length >= 6 && range.length == 0) {
        return NO;

    }
    return YES;
}

Both have the problem that when you write 6 characters then you cannot write anymore on any other text field until you delete the characters you wrote


-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if(textField.text.length >= 7 && range.length == 0)  
   {
      return NO;
   }
   return YES;
}


Implement the UITextField Delegate method:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    if(newLength > 6)
        return NO;

    return YES;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜