Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get handler of UIAlertAction in Swift

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

like image 448
borchero Avatar asked Nov 01 '25 17:11

borchero


2 Answers

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
})
like image 126
Antoine Avatar answered Nov 03 '25 11:11

Antoine


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.

like image 43
gagarwal Avatar answered Nov 03 '25 11:11

gagarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!