问题
How is it possible to get the handler of a UIAlertAction
in Swift. It is set when initializing however I haven't found any property to get hold on the closure of the action. The closure is of type (UIAlertAction) -> Void
however I would like to get the content of the closure so that I have some closure like () -> Void
. Is this possible? Thanks for your answers
回答1:
There is NO member/property exposed by the UIAlertAction class. However we can manage this by ourselves by subclassing UIAlertAction and have some member named, say, "actionHandler" to store that.
回答2:
I've created a subclass for this as followed:
/// 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)
}
}
Which can be used like this:
let myAction = UIExecutableAlertAction.with(title: "title", style: .destructive, handler: { [weak self] _ in
// Do something
})
来源:https://stackoverflow.com/questions/29084051/get-handler-of-uialertaction-in-swift