初始化UIAlertController的子类

Mar*_*dor 3 initialization subclass swift uialertcontroller

我希望创建一个自定义子类UIAlertController。如果我理解正确,则需要super.init(title...在子类初始化期间调用某处。

但是我一直遇到指定初始化程序的问题。我已经阅读了文档,无法弄清楚如何使其工作。这是我的代码(请注意代码中的注释):

class AccountInfoActionSheet: UIAlertController {

    required init?(coder aDecoder: NSCoder) { //xcode says I need this
        super.init(coder: aDecoder) //it also says I need to call a designated initializers so here it is
        super.init(title: "Info", message: "Heres the Info", preferredStyle: .actionSheet) //but now I can't call this initializer
        fatalError("init(coder:) has not been implemented")
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:由于UIAlertController不能被子类化,我只是创建了一个函数,该函数返回UIAlertController需要在ViewController内部正确配置的函数。

Ami*_*mit 6

你不应该继承UIAlertController

检查此链接:

https://developer.apple.com/documentation/uikit/uialertcontroller#//apple_ref/doc/uid/TP40014538-CH1-SW2

您可以使用添加方法,extensions但不能将其子类化。

  • 你可以,但你不应该。 (2认同)
  • 此外 - 如果您查看标题,您可以看到 UIAlertController 是一个“开放”类,而不是“最终”,因此您可以从技术上对其进行子类化,但文档明确指出您不应该这样做。你也不应该弄乱它的视图层次结构。 (2认同)