2017-08-26 101 views
0

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

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

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") 
    } 
} 

编辑:由于UIAlertController不能被继承我只是创建了返回需要它的视图控制器内的正确配置UIAlertController的功能。

回答

2

如果您想要创建通用警报控制器的更简单方法,您可以执行的操作而不是创建子类的方法是创建UIAlertController的扩展,该扩展具有工厂方法以返回所需的已配置警报控制器类型。例如:

extension UIAlertController { 

    static func accountInfo() -> UIAlertController { 
     // If you want to add Alert Actions you can add them to the controller before returning them. 
     return UIAlertController(title: "Info", message: "Here's the Info", preferredStyle: .actionSheet) 
    } 
} 

现在你可以简单地创建控制器:

let ac = UIAlertController.accountInfo() 
0

在其他的答案指出你不应该继承UIAlertController。作为一个选项,你可以用一个工厂方法创建一个扩展:

extension UIAlertController { 
    static func accountInfoActionSheet() -> UIAlertController { 
     return UIAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet) 
    } 
} 

然而,其他的答案是不是特别真实的说法,你不能继承UIAlertController。你不是应该来,但你非常多可以如果你想。

UIAlertControllerUIViewController的子类,因此它们具有相同的指定初始值设定项,即init(nibName: String?, bundle: Bundle?)

你不应该在init?(coder aDecoder: NSCoder)中调用它,因为它本身就是一个指定的构造器。例如,当控制器正在从故事板初始化时,它会被调用。

这里的例子,如何实现你想要的(尽管苹果没有批准该)什么:

class AccountInfoActionSheet: UIAlertController { 

    // preferredStyle is a read-only property, so you have to override it 
    override var preferredStyle: UIAlertControllerStyle { 
     return .actionSheet 
    } 

    init() { 
     super.init(nibName: nil, bundle: nil) 
     initialize() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     initialize() 
    } 

    // all of the configuration code that init methods might share 
    // separated into a method for the sake of convenience 
    private func initialize() { 
     title = "Info" 
     message = "Heres the Info" 
     // any other setup needed 
    } 
}