2

如何UIAlertAction在 Swift 中获取 a 的处理程序。它是在初始化时设置的,但是我没有找到任何属性来控制操作的关闭。闭包是类型,(UIAlertAction) -> Void但是我想获取闭包的内容,以便我有一些闭包,例如() -> Void. 这可能吗?感谢您的回答

4

2 回答 2

3

我为此创建了一个子类,如下所示:

/// An UIAlertAction which saves the handler. Can be used for unit testing the action callback.
final class UIExecutableAlertAction: UIAlertAction {

    private var handler: ((UIAlertAction) -> Swift.Void)?

    static func with(title: String?, style: UIAlertActionStyle, handler: ((UIAlertAction) -> Swift.Void)? = nil) -> UIExecutableAlertAction {
        let action = UIExecutableAlertAction(title: title, style: style, handler: handler)
        action.handler = handler
        return action
    }

    func execute() {
        handler?(self)
    }

}

可以这样使用:

let myAction = UIExecutableAlertAction.with(title: "title", style: .destructive, handler: { [weak self] _ in
    // Do something
})
于 2017-07-27T11:14:24.120 回答
2

UIAlertAction 类没有公开任何成员/属性。然而,我们可以通过继承 UIAlertAction 并让一些名为“actionHandler”的成员来存储它。

于 2015-03-16T18:55:57.900 回答