要控制输入到文本字段中的文本,我们需要使用委托的方式来实现。无论何时,当文本修改的时候,就会调用textField:shouldChangeCharactersInRange:replacementString:委托方法。
例如我们可以使用这个方法来限制输入的字符的个数:代码如下:
-(BOOL)textField:(UITextField *)txtField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
int MAX_CHARS = 10;
NSMutableString *newtxt = [NSMutableString stringWithString:txtField.text];
[newtxt replaceCharactersInRange:range withString:string];
return ([newtxt length] <= MAX_CHARS);
}
此段代码实现了最多允许用户输入10个字符的文本字段,但是我们应该检查替代文本的长度,而不是只看文本字段中文本的长度,因为文本字段的内容既可以是通过复制和粘贴来修改,也可以通过键盘来修改。
同样的原因,简单的把键盘类型修改为数值型,并不能确保用户只输入数字值(因为用户有可能想从字段中粘贴非数字的值)。下面的这段代码实现了这个功能:
-(BOOL)textField:(UITextField *)txtField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
for(NSInteger i =0; i< [string length]; i++)
{
unichar ch = [string characterAtIndex:i];
if(![numberSet characterIsMember:ch])
return NO;
}
return YES;
}
本文介绍如何使用委托方法控制文本字段中的文本输入,包括限制字符个数及确保输入为数字类型。通过实例代码展示实现过程。
1万+

被折叠的 条评论
为什么被折叠?



