8 iphone cocoa-touch objective-c uitextfield ios
我有UITextField以下限制 - 字符只能是数字,如下面的方法.我还想将最大字符数限制为3位数.如何修改我的方法来做到这一点?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
for (int i = 0; i < [string length]; i++) {
unichar aCharacter = [string characterAtIndex:i];
if ([aCharacterSet characterIsMember:aCharacter]) {
return YES;
}
}
NSUInteger newLength = self.textField.text.length + string.length - range.length;
return (newLength > 3) ? NO : YES;
}
Run Code Online (Sandbox Code Playgroud)
ven*_*nki 13
o限制代码下方的文本字段使用.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 3);
}
Run Code Online (Sandbox Code Playgroud)
尝试这个:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *aCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:aCharacterSet] componentsJoinedByString:@""];
if ((textField.text.length >2) && (!(string.length == 0)))
return NO;
else
return [string isEqualToString:filtered];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23914 次 |
| 最近记录: |