Character limit for multiple uitextfields

瘦欲@ 提交于 2019-12-08 05:17:40

问题


I'm a fairly new programmer and am having trouble with some UITextfields, basically i have two text fields and i want to limit the amount of characters in one of them to a certain amount, whilst allowing the other field to have lots.

I found a post that recommended this:

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

   NSUInteger newLength = [[textField text] length] + [string length] - range.length;
   return (newLength > 2) ? NO : YES;

}

However that seems to affect both text fields. I'm not sure how to target one field.

Can anyone help, also one thing, i get whats going on in that code up until - range. length, is the range the total amount of characters?


回答1:


Ok so the issue here is that the object which contains this code is the delegate to both textfields. Two ways to solve it. Either dont add the textfield you dont care about the length of as a delegate or the better way would be to differentiate between the fields during the shouldChangeCharactersInRange method.

For the second part of your question- range is the character(s) that is/are being changed in the text field and consists of: The position of the string to change, the length of the string being changed.

My personal preference is to say if the text length is greater than max length and your not deleting then refuse the change.

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

    if(textField == self.textfieldYouWantToLimitTheLengthOf){

        if(textField.text.length > 2 && ![string isEqualToString:@""]){

            return NO;
        }
    }
    return YES;
}


来源:https://stackoverflow.com/questions/12304151/character-limit-for-multiple-uitextfields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!