我有两个文本字段,我想限制字符的数量和类型。我使用以下代码分别执行每个功能,但是找不到在同一功能中同时执行这两个功能的方法。
限制字符类型:
- (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];
}
并限制字符数:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= 10 && range.length == 0)
return NO;
return YES;
}
最佳答案
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= 10 && range.length == 0)
return NO;
// 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];
}
编辑
如果要为第三个文本字段添加其他条件,则可以这样做。
创建第3个文本过滤引用
thirdField
的引用然后用这个
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == thirdField) {
//your contion e.g
if (textField.text.length < 7) {
return YES;
} else {
return NO;
}
}
else {
if (textField.text.length >= 10 && range.length == 0)
return NO;
// 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];
}
}