UIAlertView按钮响应“返回”键

时间:2014-03-25 14:25:00

标签: ios objective-c uialertview

我有UIAlertView UIAlertViewStyleSecureTextInput。当用户点击"登录"并且密码正确,它将推送下一个ViewController。如果密码不正确,则会显示另一个UIAlertView,提示单个" Dismiss"按钮。我想要做的是当用户点击返回键时,"登录"按钮将被触发。现在,当按下返回键时,警报就会解除,无论密码是否正确。也许有比我尝试过的更合乎逻辑的解决方案?对不起,如果标题有点令人困惑,我也不知道如何解释它。任何帮助是极大的赞赏。感谢。

我已在我的.h文件中声明了第一个警报,并且符合UIAlertViewDelegateUITextFieldDelegate

@interface EndViewController : UIViewController <UIAlertViewDelegate, UITextFieldDelegate>

@property (retain, strong) UIAlertView *loginRequiredMsg;

&#34;登录&#34;的方法提醒:

- (IBAction)resultsBtnPressed:(UIButton *)sender {
    self.loginRequiredMsg = [[UIAlertView alloc]initWithTitle:@"Login Required"
                                                     message:@"Please enter the admin password"
                                                    delegate:self
                                           cancelButtonTitle:@"Cancel"
                                           otherButtonTitles:@"Login", nil];
    self.loginRequiredMsg.alertViewStyle = UIAlertViewStyleSecureTextInput;
    [self.loginRequiredMsg textFieldAtIndex:0].delegate = self;
    [self.loginRequiredMsg show];
}

点击返回键时解除键盘的方法(我想如果密码不正确,我需要以某种方式调用下一个警告,因为目前它只是取消警报):

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // Dismiss keyboard when return key is pressed
    [self.loginRequiredMsg dismissWithClickedButtonIndex:self.loginRequiredMsg.firstOtherButtonIndex animated:YES];
    return YES;
}

最后输入包含密码结果的方法:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"Login"]) {
        UITextField *password = [alertView textFieldAtIndex:0];

        // Basic login authentication
        if ([password.text isEqualToString:@"admin"]) {
            // Allocate & initialise ViewController
            ResultsViewController *Results = [[ResultsViewController alloc]initWithNibName:@"ResultsViewController" bundle:nil];

            // Push next ViewController
            [self.navigationController pushViewController:Results animated:YES];
            NSLog(@"Show results");

        } else {
            UIAlertView *errorMsg = [[UIAlertView alloc]initWithTitle:@"Error"
                                                             message:@"Admin password is incorrect. Please try again."
                                                            delegate:self
                                                   cancelButtonTitle:@"Dismiss"
                                                   otherButtonTitles:nil];
            [errorMsg show];
        }
    }
}

1 个答案:

答案 0 :(得分:0)

正如评论中所讨论的,您需要实现alertView:didDismissWithButtonIndex:,它会告诉您警报视图何时被解除。当您点击返回键时,它会使用“确定”按钮的索引调用该方法。