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.
The solution is realistically almost certainly to use class extensions instead.
extension UIAlertAction {
convenience init(title: String) {
self.init(title: title, style: .Default, handler: nil)
}
}
Usage:
let okayAction = UIAlertAction(title: "Okay")
You can still subclass the UIAlertAction
to add properties to it. The subclass can still use this convience initializer you extended off of UIAlertAction
class.
Finally, for what it's worth, someone has already created a Reactive Cocoa UIAlertAction
subclass. They just did it in Objective-C. Seeing how there's no harm in adding Objective-C to your project, you could just take this approach... or just install that pod...
Like @nhgrif said, using an extension
is the way to go. It's a complementary way to write expressiveness code.
Example:
/// 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)
}
}
Use it like
alertController.addAction(.cancel)
alertController.addAction(.sharePhoto({ action in
print(action)
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With