William T.
William T.

Reputation: 14351

Re-usable UITableView "base class" with custom section header

I have a custom table view section header (set of colored lines) that I am using in around a dozen different table views. Currently, I'm cutting and pasting the same code in every single UITableViewDelegate handler.

For example, something like this:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    let lineView = UIView(frame: CGRect(x: 40, y: 0, width: tableView.frame.width - 80, height: 1))
    lineView.backgroundColor = .separator
    headerView.addSubview(lineView)
    return headerView
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 1
}

Is it possible to subclass or extend UITableView in some way so that this code is written once and automatically applied to any of my specified tableviews?

Upvotes: 2

Views: 146

Answers (1)

PGDev
PGDev

Reputation: 24341

Create a class BaseVC and conform UITableViewDelegate protocol. Implement viewForHeaderInSection and heightForHeaderInSection methods in it, i.e.

class BaseVC: UIViewController, UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        let lineView = UIView(frame: CGRect(x: 40, y: 0, width: tableView.frame.width - 80, height: 1))
        lineView.backgroundColor = .separator
        headerView.addSubview(lineView)
        return headerView
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1
    }
}

Now, inherit your ViewControllers from BaseVC like so,

class VC: BaseVC, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        return cell
    }
}

Upvotes: 2

Related Questions