[iOS] 注意自定义 AlertController 的回调时

2018-11-08  本文已影响36人  BudSwift

背景

由于 UIKitUIAlertController 的样式无法满足业务自定义的要求,所以实际开发中经常会自定义 AlertController,参考 UIAlertController 的范式,为不同的按钮事件设置不同的 block/closure/delegate 回调。以 UIAlertAction 为例:
OC

+ (instancetype)actionWithTitle:(nullable NSString *)title 
                          style:(UIAlertActionStyle)style 
                          handler:(void (^ __nullable)(UIAlertAction *action))handler;

<Swift>

public convenience init(title: String?, 
                            style: UIAlertActionStyle,
                         handler: ((UIAlertAction) -> Swift.Void)? = nil)

一般地,当点击 UIAlertController 的一个按钮时会触发对应 AlertAction 的闭包回调,比如实现 AlertController 内部的代码举例如下:

- (void)buttonClick:(UIButton *)sender {
    AlertAction *action = .....;// 找到对应 sender 的 action
    !action.handler ?: action.handler(action);
    [self dismissViewControllerAnimated:YES completion:nil];
}
func buttonClick(_ sender: UIButton) {
    let action = ...// 找到对应 sender 的 action
    action.handler?(action)
    dismiss(animated: true)
}

以上处理回调的思路可以实现

但仍旧存在一个隐患在于回调的执行时机不够完善,外部在设置 AlertAction 的 handler 时需要再次 present 一个 AlertController,则会出现异常,无法 present成功:
系统的控制台错误信息如下:

上一篇 下一篇

猜你喜欢

热点阅读