多个 uitextfields 的字符限制 [英] Character limit for multiple uitextfields

查看:49
本文介绍了多个 uitextfields 的字符限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个相当新的程序员,在使用一些 UITextfields 时遇到了问题,基本上我有两个文本字段,我想将其中一个中的字符数量限制为一定数量,同时允许另一个字段有很多.

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?

推荐答案

好的,这里的问题是包含此代码的对象是两个文本字段的委托.两种方法解决.要么不添加您不关心长度的文本字段作为委托,要么更好的方法是在 shouldChangeCharactersInRange 方法期间区分字段.

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

这篇关于多个 uitextfields 的字符限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆