简体   繁体   中英

UITableView bug? incorrect reusable cells

I have default UITableViewController with 10 row have UITableViewCell with segment control

If I change segmentController selected index in probably cell : 2, then scroll down this state of segmentController will be in other cells

cells1(selectedIndex: 1 ) cells2(selectedIndex: 1 )
cells3(selectedIndex: 1 ) cells4(selectedIndex: 1 ) cells5(selectedIndex: 1 )

... Select in cell 2 other index (2) scroll down and cell 5 have same selected index, but I am not touch them

cells1(selectedIndex: 1 ) cells2(selectedIndex: 2 )
cells3(selectedIndex: 1 ) cells4(selectedIndex: 1 ) cells5(selectedIndex: 2 )

selected 0 row

row 5 is too selected, why?

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

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

        cell.selectionStyle = .none
        cell.textLabel?.text = String(indexPath.row)
        cell.textLabel?.textColor = .white

        return cell       
    }

UITableView and UICollectionView reuse cells. Which means it only keeps enough cells in memory to show what is on the screen. As you scroll cells off the screen they are fed back in to become the cells that are appearing. You need to properly configure the cells as they re-appear in your override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

So in your case you need to set the segmented control's selection in cellForRow every time.

This means you will need a way to keep track of what selection has been made on your segmented controls and call that up to set the segmented control correctly when the cell is being shown again.

Reset selection in prepareForReuse method of UITableViewCell by subclassing it.

override func prepareForReuse() {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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