我想要一个名为 MainViewController 的可重用 View Controller ,里面有一个 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连接 - 但它们不会以您希望使用的模式“流动”。
你可以做到——在某种程度上。看看这个 SO 帖子中的讨论和答案:How to subclass custom UIViewController in Swift?
或者,如果您的目标是使用“通用” TableView Controller - 但允许自定义 - 您可以创建单独的 UITableViewDelegate
和 UITableViewDataSource
文件,以及单独的文件可视化设计的单元格,然后根据需要通过代码分配它们。
关于ios - 如何在许多子类中使用 UITableViewDelegate 对 UIViewController 进行子类化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43349940/