【问题标题】:prevent UIAlertView from dismissing防止 UIAlertView 关闭
【发布时间】:2009-12-22 17:09:36
【问题描述】:

作为一种验证形式,是否有任何方法可以防止警报视图在按下“确定”按钮时消失?

场景:我在用户名/密码的警报视图中有 2 个文本字段。如果两者都是空的并且用户按下“确定”,我不希望警报被解除。

【问题讨论】:

  • 喜欢 iTunes 密码小部件? Apple 是否为此使用 UIAlertView?

标签: objective-c uialertview


【解决方案1】:

iOS 5 为 UIAlertView 引入了一个新属性来解决这个问题。

alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;

Apple documentation on UIAlertView.

添加新的UIAlertViewDelegate 方法来处理按钮的启用/禁用。

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView

Apple documentation on UIAlertViewDelegate.

【讨论】:

    【解决方案2】:

    你做错了,你应该根据输入启用和禁用提交按钮。首先,您必须访问该按钮。这很简单,只需创建不带按钮的警报,创建一个独立的按钮并将其添加到对话框中:

    [alert addButtonWithTitle:@"OK"];
    UIButton *submitButton = [[alert subviews] lastObject];
    [submitButton setEnabled:…];
    

    然后您必须为这些文本字段设置一个委托,并在字段更改时启用或禁用按钮:

    - (BOOL) textField: (UITextField*) textField
        shouldChangeCharactersInRange: (NSRange) range
        replacementString: (NSString*) string
    {
        int textLength = [textField.text length];
        int replacementLength = [string length];
        BOOL hasCharacters = (replacementLength > 0) || (textLength > 1);
        [self setButtonsAreEnabled:hasCharacters];
    }
    
    // Disable the ‘Return’ key on keyboard.
    - (BOOL) textFieldShouldReturn: (UITextField*) textField
    {
        return NO;
    }
    

    当然,您应该将所有这些包装到一个单独的类中,这样您就不会弄乱您的调用代码。

    【讨论】:

      【解决方案3】:

      我认为您实际上不需要传递任何按钮名称。只需取出您的 OK 按钮字符串并将其保留为“nil”即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-04
        • 2012-11-22
        • 2011-10-02
        • 1970-01-01
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多