JimmyLee
JimmyLee

Reputation: 569

UITableView didSelectRowAt can't get my cell

I have a question. I have a UITableView, and four custom UITableViewCells.
When I scrolled to bottom, and I also can't get my custom UITableViewCell in didSelectRowAt function.
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])
    }

}

Upvotes: 1

Views: 579

Answers (3)

Bappaditya
Bappaditya

Reputation: 9642

To get cell in your didSelectRowAt delegate method should look like,

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)

Upvotes: 0

Nguyen Hoan
Nguyen Hoan

Reputation: 1693

enter image description here

In UITableView dequeueReusableCell- Each UITableViewCell will be reused several times with different data(image).
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. Try control with data in cellForRowAtIndexpath

Upvotes: 0

Paulw11
Paulw11

Reputation: 114856

cellForRow(at:) will return nil when the requested cell is not currently visible on the screen. When your table view scrolls to the bottom, row 0 is most likely not visible.

However, your if statement is doing its job; 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.

You should set the appearance of the row 0 cell the next time it is dequeued in your cellForRow(at:) data source method.

And, as @Bappaditya pointed out, you have a potential bounds violation crash with indexPath.row-2

Upvotes: 3

Related Questions