Получить обработчик UIAlertAction в Swift

Как можно получить обработчик UIAlertAction в Swift. Он устанавливается при инициализации, однако я не нашел никакого свойства, чтобы захватить закрытие действия. Закрытие имеет тип (UIAlertAction) -> Void, однако я хотел бы получить содержимое закрытия, чтобы у меня было какое-то закрытие, например () -> Void. Это возможно? Спасибо за ваши ответы


person borchero    schedule 16.03.2015    source источник


Ответы (2)


В классе UIAlertAction НЕТ члена/свойства. Однако мы можем справиться с этим сами, создав подкласс UIAlertAction и задав для его хранения некоторый элемент с именем, скажем, «actionHandler».

person gagarwal    schedule 16.03.2015

Я создал подкласс для этого следующим образом:

/// 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
})
person Antoine    schedule 27.07.2017