我想提供一个符合UITableViewDataSource协议的助手视图控制器。但这个类并不是有意的,必须通过继承来最终使用。
为了做到这一点,编译器要求我在helper类中实现协议。我该怎么解决这个问题?
class BigHeadViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Helper class that do ton of the job
}
class StoryTableViewController: BigHeadViewController {
// final implementation, must implement UITableViewDataSource
}
在这种情况下,您可以在超类中实现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。这将确保所需的方法在子类中实现,或者在没有子类时在控制台中向您提供错误消息(因为当没有可用的子类方法时将调用超级方法)。
在这种情况下,我会有一个UITableViewManager
,这将符合UITableViewDelegate, UITableViewDataSource
,然后我会为每个需要不同类型数据/单元格的表视图子类化它。
我会在BigHeadViewController
上有一个指向UITableViewManager
的指针,但实际上会给它分配一个UITableViewManager
的子类,比如MessageTableViewManager: UITableViewManager
然后,当您对BigHeadViewController
进行子类化时,您可以覆盖作为UITableViewManager
的var,并对if进行不同的子类以生成不同的数据。