我有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.请建议一种方法来解决这个问题。
答案 0 :(得分:2)
您手动更新文本字段中的文本,然后再发送YES
(然后再次附加字符)。然后,您使用带有替换字符串的新文本将其与两个进行比较(然后再添加您的字符)......
试试这个:
if (...) {
NSString *result = [textField.text stringByReplacingCharactersInRange:range
withString:string.uppercaseString];
if (result.length <= 2)
textField.text = result;
return NO;
}
return YES;
答案 1 :(得分:0)
要限制字符数并将其大写在UITextField中,请使用此代码块
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
textField.text = [textField.text capitalizedString];
if(textField.text.length >= 3 && range.length == 0)
{
return NO;
}
else
{
return YES;
}
答案 2 :(得分:0)
请尝试使用这个...它可能对你有所帮助
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:[string capitalizedString]])
{
NSString *result = [textField.text stringByReplacingCharactersInRange:range
withString:string.uppercaseString];
if (result.length <= 2)
textField.text = result;
return NO;
}
else
return YES;
}
答案 3 :(得分:0)
登录UITextFieldTextDidChangeNotification
在此做出判断
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textChanged:)
name:UITextFieldTextDidChangeNotification
object:YOUR_TEXT_FIELD];
-(void)textChanged:(NSNotification *)notif {
//to do your logic
}