LateNate
LateNate

Reputation: 891

didSelectRowAt not called in custom UITableView

After some refactoring I decided to create a custom tableview that looks a bit like:

class BaseTable: UITableView, UITableViewDelegate, UITableViewDataSource {

var rowsInSection: Int { return  0}

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

        self.delegate = self
        self.dataSource = self
        self.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    }

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

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

        return cell
        }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.deselectRow(at: indexPath, animated: true)
        }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "headerCell")!
        return cell
    }

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

And then I subclass it like this:

class CustomTable: BaseTable{
    override var rowsInSection: Int {return payArray.count }
}

This works fine, however I've noticed none of the subclassed didSelectRowAt are being called??? Can anyone help?

Upvotes: 0

Views: 404

Answers (2)

funct7
funct7

Reputation: 3591

This is bad design. The reason there are delegate and data source protocols for UITableViews is because view objects should be reusable. You're making your BaseTable class to function as a controller as well as a view.

To answer your question, are you sure it's not being called? You only have deselectRow(at:animated:) calling from tableView(didSelectRowAt:)

Upvotes: 0

Igor Kislyuk
Igor Kislyuk

Reputation: 330

Well, you should follow this things:

  1. You should split up logic from initWithCoder: to external method such as and call it in initWithFrame:, because different approaches called different init methods. Such as

func setUpTableView() { self.delegate = self self.dataSource = self self.register(UITableViewCell.self, forCellReuseIdentifier: "cell") }

  1. For clarity in your code, you should explicitly call super method from child class methods
  2. Otherwise, I strongly recommend you not to use this approach, better use standard UITableView in controller, and different classes, that implements protocols alongside with custom UITableViewCell's

Upvotes: 1

Related Questions