1

I would like to have a reusable view controller called MainViewController with a UITableView inside.

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

I need to have many subclasses of my MainViewController, to can custom them depending of my needs. IntroViewController is one of them.

class IntroViewController: MainViewController {

}

To open the IntroViewController, here my 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
    }

}

I got this crash:

fatal error: unexpectedly found nil while unwrapping an Optional value

for the line

self.tableView.dataSource = self

I checked, my outlets are linked correctly. Datasource too.

cmii
  • 3,556
  • 8
  • 38
  • 69

1 Answers1

0

What you're trying to do doesn't really work that way. The @IBOutlets are all connected through the Storyboard - but they don't "flow through" in the pattern you're hoping to use.

You can do it - in a way. Take a look a the discussion and answers in this SO post: How to subclass custom UIViewController in Swift?

Alternatively, if you're goal is to use a "common" table view controller - but allow customization - you can create separate UITableViewDelegate and UITableViewDataSource files, plus separate visually designed cells, and then assign them via code as desired.

Community
  • 1
  • 1
DonMag
  • 69,424
  • 5
  • 50
  • 86