【问题标题】:How to subclass an UIViewController with UITableViewDelegate in many subclasses如何在许多子类中使用 UITableViewDelegate 子类化 UIViewController
【发布时间】:2017-04-11 15:16:13
【问题描述】:

我想要一个名为 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,这里是我的转场:

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

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

【问题讨论】:

  • 什么是 StoryViewController ?
  • MainViewController,我更正了。
  • 为什么在两个控制器之间导航控制器。?
  • 你给表控制器的类名了吗?
  • 我可以使用自定义 segue 而不是导航控制器

标签: ios swift uitableview uiviewcontroller subclass


【解决方案1】:

您尝试做的事情并没有真正起作用。 @IBOutlets 都通过故事板连接 - 但它们不会以您希望使用的模式“流过”。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多