【问题标题】:How to provide an inherited view controller that support a UITableViewDataSource protocol?如何提供支持 UITableViewDataSource 协议的继承视图控制器?
【发布时间】:2016-04-12 16:02:35
【问题描述】:

我想提供一个符合 UITableViewDataSource 协议的辅助视图控制器。但是这个类不是有意的,必须通过继承来终结。

试图这样做,编译器要求我在帮助类中实现协议。 我该如何解决这个问题?

class BigHeadViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    // Helper class that do ton of the job
}

class StoryTableViewController: BigHeadViewController {
    // final implementation, must implement UITableViewDataSource
}

【问题讨论】:

    标签: ios swift inheritance protocols


    【解决方案1】:

    在这种情况下,您可以在超类中实现 UITableViewDataSource 方法,其内容如下:

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    
        precondition(false, "UITableViewDataSource method MUST be implemented in subclass of BigHeadViewController")    
    
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        precondition(false, "UITableViewDataSource method MUST be implemented in subclass of BigHeadViewController") 
    
        return 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        precondition(false, "UITableViewDataSource method MUST be implemented in subclass of BigHeadViewController") 
    
        return UITableViewCell()
    }
    

    当你在你的子类中实现 UITableViewDataSource 方法时,不要调用 super。这将确保所需的方法在子类中实现,或者在没有实现时在控制台中向您提供错误消息(因为在没有可用的子类方法时将调用超级方法)。

    【讨论】:

      【解决方案2】:

      在这种情况下,我将有一个 UITableViewManager,这将符合 UITableViewDelegate, UITableViewDataSource,然后我将为每个需要不同类型的数据/单元格的 tableview 子类化它。

      我会在BigHeadViewController 上有一个指向UITableViewManager 的指针,但实际上会为其分配UITableViewManager 的子类,例如MessageTableViewManager: UITableViewManager

      然后,当您将 BigHeadViewController 子类化时,您可以覆盖 UITableViewManager 的 var 并制作不同的 if 子类以生成不同的数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多