Erent
Erent

Reputation: 621

How to override tableView style in a subclass

I have a superclass that is used in many places and its a just a class that conforms to tableView delegates.


    class SuperTableViewController: UITableViewDataSource, UITableViewDelegate {

        var tableView: UITableView = {

            let tableView = UITableView(frame: .zero, style: .plain)

            return tableView
        }()

    ... //more code

    }

I want to create a subclass that inherits from the SuperTableViewController but it should have a grouped style, I am not sure how to override the tableview style in the subclass:


    class SubClassController: SuperTableViewController {

        override func viewDidLoad() {
            super.viewDidLoad()

     tableView = UITableView(frame: .zero, style: .grouped) // this doesn't work
    }

    ... //more code

    }

Upvotes: 1

Views: 337

Answers (2)

Kamran
Kamran

Reputation: 15258

You can introduce a tableView style property in the SuperTableViewController as below and override in the subClasses. This way you don't have to initialize the whole tableView or register cells altogether in subClasses.

class SuperTableViewController: UITableViewDataSource, UITableViewDelegate {

    var tableViewStyle: UITableView.Style {
        return .plain
    }

    lazy var tableView: UITableView = {
         let tableView = UITableView(frame: .zero, style: self.tableViewStyle)
         return tableView
    }()
}

class SubClassController: SuperTableViewController {

    override var tableViewStyle: UITableView.Style {
        return .grouped
    }
}

Upvotes: 2

PGDev
PGDev

Reputation: 24341

First of all, since you're inheriting SuperTableViewController as a UIViewController in SubClassController, so SuperTableViewController must be of type UIViewController.

class SuperTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        return tableView
    }()
}

Then in SubClassController's viewDidLoad() methods, you can simply se a new instance of tableView using grouped style, i.e.

class SubClassController: SuperTableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView = UITableView(frame: .zero, style: .grouped)
    }
}

Upvotes: 0

Related Questions