我有 4 个文本字段,我想在其中同时设置两个限制。一是用户应该只能输入大写字母,最大字符数限制为 2。我的代码如下:-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
// Below logic is for All 4 Modifer Textfields
// we are restrict the user to enter only max 2 characters in modifier textfields.
if (textField==txt_modifier1 || textField==txt_modifier2 || textField==txt_modifier3 ||
textField==txt_modifier4) {
textField.text = [textField.text stringByReplacingCharactersInRange:range
withString:[string
uppercaseStringWithLocale:[NSLocale currentLocale]]];
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 2) ? NO : YES;
}
return YES;
这不能正常工作,因为它会在我输入任何字符时再追加一个字符,并且也不会将字符数限制为 2 个。请提出解决此问题的方法。
最佳答案
您正在手动更新文本字段中的文本,然后发送回 YES
(然后第二次附加字符)。然后,您使用带有替换字符串的新文本将其与两个进行比较(然后再次附加您的字符)...
试试这个:
if (...) {
NSString *result = [textField.text stringByReplacingCharactersInRange:range
withString:string.uppercaseString];
if (result.length <= 2)
textField.text = result;
return NO;
}
return YES;
关于iphone - 限制用户输入字符,并在ios中将每个输入的字母转换为大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16396819/