2017-08-26 103 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 
    } 
}