如何快速覆盖 UIAlertController 中的便利初始化? [英] How can I override convenience init in UIAlertController for swift?
问题描述
我正在尝试覆盖 UIAlertController 中的便捷初始化,但它给了我一个错误,例如初始化程序不会覆盖其超类中的指定初始化程序".如何使用继承或扩展来覆盖它?我的代码如下.
I'm trying to override convenience init in UIAlertController, but it gives me an error like 'initializer does not override a designated initializer from its superclass'. How can I override it using inheritance or extension whatever? My codes are below.
import UIKit
class ColorAlertViewController: UIAlertController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override convenience init(title: String?, message: String?, preferredStyle: UIAlertControllerStyle, colorCode: String?){
super.init(title: title, message: message, preferredStyle: preferredStyle)
}
}
推荐答案
你没有覆盖任何便利的 init,看起来你正在创建一个新的.
you are not overriding any convenience init, it looks like you are creating a new one.
convenience init(title: String?, message: String?, preferredStyle: UIAlertControllerStyle, colorCode: String?){
self.init(title: title, message: message, preferredStyle: preferredStyle)
}
可能就是你想要的,你只需要处理颜色代码
Is probably what you want, you just need to handle the color code
看来您将不得不绕道而行:
Looks like you are going to have to go a round about way:
首先创建一个创建扩展
extension UIAlertController
{
class func create(title: String?, message: String?, preferredStyle: UIAlertControllerStyle) -> AnyObject
{
return UIAlertController(title: title, message: message, preferredStyle: preferredStyle);
}
}
然后在 ColorAlertViewController 中,您将创建另一个函数来创建此对象:
Then in the ColorAlertViewController, you will create another function to create this object:
class func createWithColor(title: String?, message: String?, preferredStyle: UIAlertControllerStyle, colorCode: String?) -> AnyObject
{
var c = super.create(title, message: message, preferredStyle: preferredStyle);
//handle color code here
return c;
}
现在你想在任何地方创建这个对象,只要调用
Now anywhere you want to create this object, just call
var colorAlertView = ColorAlertViewController.createWithColor("title Name", message: "the message", preferredStyle: .ActionSheet, colorCode: "the color");
当然这在 UI 构建器中不起作用,您必须通过代码创建它.
of course this won't work inside the UI builder, you would have to create this via code.
这篇关于如何快速覆盖 UIAlertController 中的便利初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!