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

标签 ios swift uitableview uiviewcontroller subclass

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

我需要有许多 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

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

最佳答案

您尝试做的事情并不是那样有效。 @IBOutlets 全部通过 Storyboard连接 - 但它们不会以您希望使用的模式“流动”。

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

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

关于ios - 如何在许多子类中使用 UITableViewDelegate 对 UIViewController 进行子类化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43349940/

相关文章:

ios - Swift 中的核心数据 : Only saving last object in a for loop

xcode - 在 Swift 上向侧边栏菜单添加功能

ios - UITableView reloadData 似乎不会导致 cellForRowAtIndexPath : to be called

ios - '-[__NSCFArray objectAtIndex :]: index (1) beyond bounds (1)' after item added to array

ios - 只允许特定部分在 UITableView 中滚动

ios - 错误域=NSCocoaErrorDomain代码=3840“字符周围的值无效

ios - 3 个文本字段,1 个 pickerview,但是,使用 pickerView 时,选择内容不会显示在文本字段中

ios - flutter : Unable to redirect to specific screen on Notification click when app is in background but not terminated in iOS

ios - ios Google Analytics(分析)广告系列跟踪

ios - 二元运算符 '<^>' 不能应用于类型的操作数