禁用UIAlertView按钮

12

我正在使用文本输入创建一个UIAlertView

UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"Save" message:@"Please Enter the Name of PDF" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alertView setAlertViewStyle:UIAlertViewStylePlainTextInput]

当UITextField为空时,我想通过委托函数禁用OK按钮

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{

return NO;
}

当用户开始在文本框中输入内容时,OK按钮应该变为可用状态。


那么一旦 UIAlertView 弹出,就没有取消和关闭它的按钮了吗? - Desdenova
2个回答

34
请尝试这个。
    - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
    {
        /* Retrieve a text field at an index - 
           raises NSRangeException when textFieldIndex is out-of-bounds.

         The field at index 0 will be the first text field
         (the single field or the login field),

         The field at index 1 will be the password field. */

         /*
         1> Get the Text Field in alertview

         2> Get the text of that Text Field

         3> Verify that text length

         4> return YES or NO Based on the length
         */

         return [alertView textFieldAtIndex:0].text.length > 0;

    }

2
你实际上可以直接返回; 三元运算符是多余的。 return ([[[alertView textFieldAtIndex:0] text] length]>0) - Joe

10

你应该更好地利用那个UIAlertViewDelegate方法:

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    UITextField *textField = [alertView textFieldAtIndex:0];
    if ([textField.text length] == 0){
        return NO;
    }
    return YES; 
}
请注意,这是iOS 5.0中引入的新的委托方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接