【发布时间】:2019-04-22 09:06:27
【问题描述】:
我正在为我的应用创建自定义对话框,并在某些方面复制 UIAlertController。我应该如何实现当您单击警报/对话框中的任何操作时控制器被解除的行为。
Apple 如何在不让我们手动为每个动作处理程序指定它应该关闭视图控制器的情况下做到这一点?
我喜欢他们一个视图控制器类:
@interface MyAlertViewController : UIViewController
- (void)addAction:(MyAlertAction *) action;
//...
还有一类动作:
@interface MyAlertAction : NSObject
- (instancetype)initWithTitle:(nullable NSString *)title handler:(void (^)(MyAlertAction *action))handler;
编辑:根据答案反馈,我是如何做到的:
//MYAlertViewController.m
- (void)viewDidLoad {
for (int i = 0; i < self.actions.count; i++) {
MYAlertAction *action = self.actions[i];
button = [[UIButton alloc] initWithFrame:CGRectZero];
button.tag = i;//this here is how I link the button to the action
[button addTarget:self action:@selector(executeAction:) forControlEvents:UIControlEventTouchUpInside];
[actionStackView addArrangedSubview:button];
[self.actionsStackView addArrangedSubview:actionLayout];
}
}
- (void)executeAction:(UIButton *) sender{
[self dismissViewControllerAnimated:YES completion:^{
//this is where the button tag comes in handy
MYAlertAction *actionToExecute = self.actions[sender.tag];
actionToExecute.actionHandler();
}];
}
【问题讨论】:
-
屏幕上的每个按钮都与一个动作相关联。当按钮被触发时,控制器被解除并触发动作
-
顺便说一句,如果执行是按照你说的顺序。关闭具有动作引用的控制器后,动作如何执行?
-
我不喜欢使用标签和索引。我个人会将每个块存储在按钮本身中。
标签: ios objective-c