UIAlertview 在未调用索引委托方法时单击了按钮

UIAlertview clicked button at index delegate method not being called

我是具有操作的 AlertViews 的新手。按照我在此处找到的示例设置我的设置,包括在我的 .h 中设置委托方法,但是当我调试时发现它没有到达我的 clickedButtonAtIndex 方法。可能遗漏了一些简单的东西:-/ 任何解决这个问题的帮助将不胜感激,谢谢。 这是我的代码:

.h 文件

@interface LineDetailViewController : UIViewController <UIAlertViewDelegate>

。 m 文件:

- (IBAction)removeLineButton:(UIButton *)sender {

    NSString * requestSubmitText = [NSString stringWithFormat:@"Hey Bro are you sure you want to remove this line you created, it will also remove all the reviews attached and can not be undone?"];

    UIAlertView *removeLineRequest = [[UIAlertView alloc] initWithTitle:@"WARNING!!"
                                                          message:requestSubmitText
                                                         delegate:nil
                                                cancelButtonTitle:@"Remove It"
                                                otherButtonTitles:@"Cancel",nil];
    [removeLineRequest show];

- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex{
    //if (buttonIndex == [alertView cancelButtonIndex]){
    if (buttonIndex == 0){
        NSLog(@"Cancel button pressed");
    }else{
        NSLog(@"other button pressed");
    }
}

您必须将委托设置为 self

UIAlertView *removeLineRequest = [[UIAlertView alloc] initWithTitle:@"WARNING!!"
                                                          message:requestSubmitText
                                                         delegate:self // <- here
                                                cancelButtonTitle:@"Remove It"
                                                otherButtonTitles:@"Cancel",nil];

呼叫removeLineRequest.delegate = self.

在创建警报视图时将委托设置为 self 。并且您已经实现了 UIAlertView Delegate。

要解决您的问题,只需将 delegate 设置为 self 而不是 nil。 一些额外的信息,

UIAlertViewUIAlertViewDelegate 已被弃用。根据文档,

UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.

相关教程here