如何在许多子类中使用 UITableViewDelegate 对 UIViewController 进行子类化

How to subclass an UIViewController with UITableViewDelegate in many subclasses

我想要一个名为 MainViewController 的可重用视图控制器,里面有一个 UITableView。

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView : UITableView!

    override func viewDidLoad() {

        super.viewDidLoad()

        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.scrollsToTop = true

        self.tableView.estimatedRowHeight = 124.0
        self.tableView.rowHeight = UITableViewAutomaticDimension
}

我需要有许多 MainViewController 的子类,以便可以根据我的需要自定义它们。 IntroViewController 就是其中之一。

class IntroViewController: MainViewController {

}

要打开 IntroViewController,这里是我的 segue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "intro" {

        let destination =  segue.destination as! UINavigationController
        let ivc = destination.topViewController as! IntroViewController
    }

}

我遇到了这个崩溃:

fatal error: unexpectedly found nil while unwrapping an Optional value

self.tableView.dataSource = self

我检查过,我的网点链接正确。数据源也是。

您尝试做的事情并不是那样有效。 @IBOutlets 都通过 Storyboard 连接 - 但它们不会 "flow through" 您希望使用的模式。

可以做到——在某种程度上。看看这个 SO post 中的讨论和答案:

或者,如果您的目标是使用 "common" table 视图控制器 - 但允许自定义 - 您可以创建单独的 UITableViewDelegateUITableViewDataSource 文件,加上单独的视觉设计单元格,然后根据需要通过代码分配它们。