这是我的代码:
class CustomAlertAction: UIAlertAction {
init(title : String) {
super.init(title: title, style: UIAlertActionStyle.Default) { (action) -> Void in
}
}
}
但是我得到了以下编译错误:
Must call a designated initializer of the superclass 'UIAlertAction'
我知道 UIAlertAction 的指定初始化程序是 init()。但是 UIAlert 的 init(title, style, handler) 不会调用它指定的初始化器 init()?
有什么想法吗?谢谢
P.S. 基于 Apple 文档:
A designated initializer must call a designated initializer from its immediate superclass.”
这是否意味着在Swift中不允许继承UIAlertAction?在 Objective-C 中这样做是没有问题的。
我之所以要创建一个 UIAlertAction 的子类,是因为我想添加一个 ReactiveCocoa 命令作为一个 Action 。
最佳答案
解决方案实际上几乎肯定是使用类扩展。
extension UIAlertAction {
convenience init(title: String) {
self.init(title: title, style: .Default, handler: nil)
}
}
用法:
let okayAction = UIAlertAction(title: "Okay")
您仍然可以子类化 UIAlertAction
以向其添加属性。子类仍然可以使用您从 UIAlertAction
类中扩展出来的这个方便的初始值设定项。
最后,不管怎样,someone has already created a Reactive Cocoa UIAlertAction
subclass .他们只是在 Objective-C 中做到了。看到将 Objective-C 添加到您的项目并没有什么坏处,您可以只采用这种方法……或者只安装那个 pod……
关于ios - 在 Swift 中继承 UIAlertAction 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31419294/