didSelectRow未在自定义UITableView

时间:2016-10-05 21:31:14

标签: ios swift uitableview

经过一些重构后,我决定创建一个看起来有点像的自定义tableview:

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
    }

然后我像这样继承它:

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

这样可以正常工作,但是我注意到没有一个子类的didSelectRowAt被调用了???有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

嗯,你应该遵循这些事情:

  1. 您应该将逻辑从initWithCoder:拆分为外部方法,并在initWithFrame:中调用它,因为不同的方法称为不同的init方法。如
  2. func setUpTableView() { self.delegate = self self.dataSource = self self.register(UITableViewCell.self, forCellReuseIdentifier: "cell") }

    1. 为了清楚您的代码,您从子类方法显式调用super方法
    2. 否则,我强烈建议您不要使用此方法,最好在控制器中使用标准UITableView,以及在自定义UITableViewCell&#下实现协议的不同类39; S

答案 1 :(得分:0)

这是糟糕的设计。有UITableView的委托和数据源协议的原因是因为视图对象应该是可重用的。您正在使BaseTable类充当控制器和视图。

要回答你的问题,你确定它没有被调用吗?您只能deselectRow(at:animated:)

进行tableView(didSelectRowAt:)来电