Get handler of UIAlertAction in Swift

浪尽此生 提交于 2020-05-29 11:28:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!