user2343632
user2343632

Reputation: 310

Pass storyboard outlet to base controller class

I have a base class:

class BaseViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITableViewDataSourcePrefetching {
    var posts = [Post]()

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostTableViewCell", for: indexPath) as? PostTableViewCell else {
            fatalError("The dequeued cell is not an instance of PostTableViewCell.")
        }

        let post = posts[indexPath.row]

        cell.parentViewController = self
        cell.initialize(post: post)

        return cell
    }
}

That I use as a subclass:

class FeedViewController: BaseViewController {
    @IBOutlet weak var tableView: UITableView!

    // Other stuff
}

I use the base class to handle all table view functions (which I reuse in many parts of my app).

In my storyboard, I have a controller design set up for FeedViewController, with a table view. However, I'm not sure how to pass my storyboard outlet, which is currently connected to FeedViewController to my base controller, so that the base controller handles all the table view logic. How would I do this?

Upvotes: 1

Views: 347

Answers (1)

Asperi
Asperi

Reputation: 258393

If you don't instantiate BaseViewController in code directly, then just move outlet declaration in base class (storyboard will handle this automatically)

class BaseViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITableViewDataSourcePrefetching {
    @IBOutlet weak var tableView: UITableView!

    // Other stuff
}

class FeedViewController: BaseViewController {

    // Other stuff
}

Upvotes: 2

Related Questions