【问题标题】:How to deal with different UIAlertAction handler in same UIAlertController in iOS?如何在 iOS 的同一个 UIAlertController 中处理不同的 UIAlertAction 处理程序?
【发布时间】:2016-01-05 13:09:29
【问题描述】:

我正在使用 Objective-C 编写一些 UIAlertController 代码。

我有更多按钮,但是按钮会显示不同的UIAlertControllers 并处理不同的UIAlertAction 处理程序。

所以我想创建一个UIAlertControllerUIAlertAction

如下:

-(void) initAlert{
    alertController = [UIAlertController alertControllerWithTitle:@"hint" message:@"count down alert" preferredStyle:UIAlertControllerStyleAlert];

    doneAction = [UIAlertAction actionWithTitle:@"okey" style:UIAlertActionStyleDefault handler:
              ^(UIAlertAction *action) {
    NSLog(@"show log");
    }];
    [alertController addAction:doneAction];
}

-(void) showAlert{
    [self presentViewController:alertController animated:YES completion:nil];
}

然后我想用不同的按钮IBAction调用showAlert方法,并设置不同的UIAlertController标题,UIAlertAction标题和处理不同的alertAction处理程序。

但是我遇到了一些问题。

我在不同的按钮中调用该方法,如下所示:

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

    alertController.title = @"controller 1";
    alertController.message = @"message1";

    [self showAlert];
}

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

    alertController.title = @"controller 2";
    alertController.message = @"message2";

    [self showAlert];
}

我不知道如何用相同的 doneAction 更改 UIAlertAction 标题,我搜索了一些数据显示 UIAlertAction 是 readyonly 属性。

那么还有其他方法可以更改UIAlertAction 标题吗?或者我们可以删除UIAlertControlleraddAction:方法添加其他UIAlertAction吗?

我如何将不同的 UIAlertAction 处理程序传递给 AlertAction 以供相同的 UIAlertController 使用?

非常感谢。

【问题讨论】:

  • 我不认为 UIAlertController 是为可重用性而设计的。您应该为不同的警报创建不同的 UIAlertController。

标签: ios objective-c uialertcontroller uialertaction


【解决方案1】:

UIAlertController 不应多次使用。每次要弹出警报时,只需使用一个新的 UIAlertController 实例即可。

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

    [self showAlert:@"Controller 1" message:@"Message 1" handler:^(UIAlertAction *action) {
        NSLog(@"btn1Action");
    }];
}

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

    [self showAlert:@"Controller 2" message:@"Message 2" handler:^(UIAlertAction *action) {
        NSLog(@"btn2Action");
    }];
}

-(void)showAlert:(NSString*)alertTitle message:(NSString*)message handler:(void (^ __nullable)(UIAlertAction *action))handler {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:alertTitle message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction * doneAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:handler];
    [alertController addAction:doneAction];

    [self presentViewController:alertController animated:YES completion:nil];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多