0

我有 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。请提出一种解决此问题的方法。

4

4 回答 4

2

您正在手动更新文本字段中的文本,然后发YES回(然后再次附加字符)。然后,您使用带有替换字符串的新文本将其与两个进行比较(然后再次附加您的字符)......

尝试这个:

if (...) {
    NSString *result = [textField.text stringByReplacingCharactersInRange:range
                                                               withString:string.uppercaseString];
    if (result.length <= 2)
        textField.text = result;
    return NO;
}
return YES;
于 2013-05-06T10:43:08.833 回答
0

登录UITextFieldTextDidChangeNotification这里做判断

[[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(textChanged:)
                                              name:UITextFieldTextDidChangeNotification
                                            object:YOUR_TEXT_FIELD];

-(void)textChanged:(NSNotification *)notif {
    //to do your logic
}
于 2013-05-07T05:22:32.707 回答
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;
}
于 2013-05-06T10:51:39.670 回答
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;
            }
于 2013-05-06T10:38:20.827 回答