我使用Objective-C来编写一些UIAlertController
代码。
我有更多按钮,但按钮会显示不同的UIAlertController
并处理不同的UIAlertAction
处理程序。
所以我想创建一个UIAlertController
和UIAlertAction
。
如下所示:
-(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
已准备好属性。
那么还有其他方法可以更改UIAlertAction
标题吗?或者我们可以删除UIAlertController
addAction:
方法以添加其他UIAlertAction
吗?
如何将不同的UIAlertAction
处理程序传递给AlertAction,以便使用相同的UIAlertController
?
非常感谢。
答案 0 :(得分:0)
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];
}