5

Here is my code:

class CustomAlertAction: UIAlertAction {
    init(title : String) {
        super.init(title: title, style: UIAlertActionStyle.Default) { (action) -> Void in
        }
    }
}

But I got the following compiling error:

Must call a designated initializer of the superclass 'UIAlertAction'

I know the designated initializer of UIAlertAction is init(). But the init(title, style, handler) of UIAlert will not call its designated initializer init()?

Any idea? Thanks

P.S.: Based on the Apple's document:

A designated initializer must call a designated initializer from its immediate superclass.”

Does this mean it's not allowed to inherit UIAlertAction in Swift? It's no problem to do so in Objective-C.

The reason why I want to create a subclass of UIAlertAction is because I want to add a ReactiveCocoa command as an action.

4

3 に答える 3

1

@nhgrifが言ったように、を使用するのextensionが道です。これは、表現力のコードを記述するための補完的な方法です。

例:

/// App alert actions
extension UIAlertAction {
    static var cancel: UIAlertAction {
        return UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
    }
    class func sharePhoto(handler: ((UIAlertAction) -> Void)?) -> UIAlertAction {
        return UIAlertAction(title: "Share", style: .Default, handler: handler)
    }
}

のように使う

alertController.addAction(.cancel)

alertController.addAction(.sharePhoto({ action in
    print(action)
}))
于 2016-10-28T19:58:45.393 に答える