小编Too*_*ool的帖子

UITextField限制字符的数量和类型

我有两个文本字段,我想限制字符的数量和类型.我已经使用以下代码来单独执行每个功能,但无法在同一个函数中找到两种方法.

要限制字符的类型:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // Only characters in the NSCharacterSet you choose will insertable.
    NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}
Run Code Online (Sandbox Code Playgroud)

并限制字符数:

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

iphone objective-c ios

12
推荐指数
1
解决办法
1万
查看次数

标签 统计

ios ×1

iphone ×1

objective-c ×1