【发布时间】:2015-03-16 18:12:47
【问题描述】:
如何在 Swift 中获取 UIAlertAction 的处理程序。它是在初始化时设置的,但是我没有找到任何属性来控制操作的关闭。闭包的类型为(UIAlertAction) -> Void,但是我想获取闭包的内容,以便我有一些闭包,例如() -> Void。这可能吗?谢谢你的回答
【问题讨论】:
标签: swift uialertcontroller uialertaction
如何在 Swift 中获取 UIAlertAction 的处理程序。它是在初始化时设置的,但是我没有找到任何属性来控制操作的关闭。闭包的类型为(UIAlertAction) -> Void,但是我想获取闭包的内容,以便我有一些闭包,例如() -> Void。这可能吗?谢谢你的回答
【问题讨论】:
标签: swift uialertcontroller uialertaction
我为此创建了一个子类,如下所示:
/// 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
})
【讨论】:
UIAlertAction 类没有公开任何成员/属性。然而,我们可以通过继承 UIAlertAction 并让一些名为“actionHandler”的成员来存储它。
【讨论】: