alertViewShouldEnableFirstOtherButton iOS5中的无限循环

时间:2012-12-10 16:38:47

标签: ios5 ios6 uialertview

我试图在方法alertViewShouldEnableFirstOtherButton中将用户输入的第一个字母更改为大写字母。一切都在iOS 6中按预期工作,但在iOS 5中似乎我得到了无限循环(当我以编程方式设置警报视图的文本字段时,它以递归方式调用方法alertViewShouldEnableFirstOtherButton) 这是代码:

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView{
    NSString *inputText = [[alertView textFieldAtIndex:0] text];
    if(inputText.length==0)return NO;

    unichar firstChar=[[inputText capitalizedString] characterAtIndex:0];
    NSString *capitalizedLetter= [NSString stringWithCharacters:&firstChar length:1];
    NSString *str=[inputText stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:capitalizedLetter];

   [[alertView textFieldAtIndex:0] setText:str];// setText calls again alertViewShouldEnableFirstOtherButton
    return YES;

}

2 个答案:

答案 0 :(得分:0)

- (BOOL)alertViewShouldEnableFirstOtherButton:用于alertView询问其代理是否应启用第一个(非取消)按钮。 alertView可以随时调用此方法(例如,当文本字段更改时可以调用它),从代理获得YES / NO答案。因此,您不应在此处实施副作用。

我建议使用[alertView textFieldAtIndex:0].delegate = self之类的东西,并使用textField委托方法之一(例如– textFieldDidBeginEditing:)来修改字符串。

答案 1 :(得分:0)

实际上我使用了shouldChangeCharactersInRange UITextField方法来大写插入字符串的第一个字母。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSLog(@"range: %@ string: %@", NSStringFromRange(range), string);
    if ([string isEqualToString:@""]) {// detect when the user removes symbol
        if ([textField.text length] > 0)textField.text = [textField.text substringToIndex:[textField.text length] - 1];//remove last character from the textfield 
    }
    if (range.location==0) {//capitalize first letter
        NSString *upperString = [[textField.text stringByAppendingString:string] uppercaseString];
        textField.text = upperString;
    }else {
        textField.text=[textField.text stringByAppendingString:string];
    }
    return NO;
}
相关问题