简体   繁体   English

UITableView didSelectRowAt无法获取我的单元格

[英]UITableView didSelectRowAt can't get my cell

I have a question. 我有个问题。 I have a UITableView, and four custom UITableViewCells. 我有一个UITableView和四个自定义UITableViewCells。
When I scrolled to bottom, and I also can't get my custom UITableViewCell in didSelectRowAt function. 当我滚动到底部时,我也无法在didSelectRowAt函数中获取我的自定义UITableViewCell。
Please give me some advice. 请给我一些建议。
Thanks. 谢谢。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if let cell: ChartTableViewCell = customTableview.cellForRow(at: IndexPath(row: 0, section: 0)) as? ChartTableViewCell {
        printBBLog("here.") //just When I scrolled to bottom, this don't print.
        let colors = AssetViewController.Color.getAllColors()
        cell.barChartView?.tapIndexWithColor(index: indexPath.row-2, color: colors[indexPath.row-2])
    }

}

cellForRow(at:) will return nil when the requested cell is not currently visible on the screen. 当所请求的单元格当前在屏幕上不可见时, cellForRow(at:)将返回nil When your table view scrolls to the bottom, row 0 is most likely not visible. 当您的表格视图滚动到底部时,第0行很可能不可见。

However, your if statement is doing its job; 但是,你的if语句正在发挥作用; if cellForRow(at:) returns nil you don't have a cell to update and so you don't need to do anything in that function. 如果cellForRow(at:)返回nil ,则没有要更新的单元格,因此您不需要在该函数中执行任何操作。

You should set the appearance of the row 0 cell the next time it is dequeued in your cellForRow(at:) data source method. 下一次在cellForRow(at:)数据源方法中出列时,应设置行0单元格的外观。

And, as @Bappaditya pointed out, you have a potential bounds violation crash with indexPath.row-2 而且,正如@Bappaditya指出的那样,你有一个潜在的边界违规崩溃与indexPath.row-2

To get cell in your didSelectRowAt delegate method should look like, 要在didSelectRowAt委托方法中获取单元格应该是这样的,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let indexPath = tableView.indexPathForSelectedRow()
    let cell = tableView.cellForRow(at: indexPath) as! ChartTableViewCell
    let colors = AssetViewController.Color.getAllColors()
    cell.barChartView?.tapIndexWithColor(index: indexPath.row-2, color: colors[indexPath.row-2])
}

And to keep the table view at top, you may want to use, 并且要将表格视图保持在顶部,您可能想要使用,

scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)

在此输入图像描述

In UITableView dequeueReusableCell- Each UITableViewCell will be reused several times with different data(image). 在UITableView dequeueReusableCell中 - 每个UITableViewCell将使用不同的数据(图像)重复使用几次。
In your case, When you scrolled to bottom, cell at IndexPath(row: 0, section: 0) was reused by another cell that is displaying at the botttom, so you can't config this cell. 在您的情况下,当您滚动到底部时, IndexPath(row: 0, section: 0)处的单元格被底部显示的另一个单元格重用,因此您无法配置此单元格。 Try control with data in cellForRowAtIndexpath 尝试使用cellForRowAtIndexpath数据进行控制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM