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

时间:2017-04-11 15:16:14

标签: ios swift uitableview uiviewcontroller subclass

我想有一个名为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

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

class IntroViewController: MainViewController {

}

打开IntroViewController,这里是我的segue:

UINavigationController

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

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

1 个答案:

答案 0 :(得分:0)

您尝试做的事情并非如此。 @IBOutlets都是通过故事板连接的 - 但是他们并没有通过"在你希望使用的模式中。

可以在某种程度上做到这一点。在这篇SO帖子中查看讨论和答案:How to subclass custom UIViewController in Swift?

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