UITableView错误?错误的可重复使用的细胞

问题描述 投票:0回答:2

我有10行的默认UITableViewController有UITableViewCell与段控件

如果我在可能的cell:2中更改了segmentController选择的索引,那么向下滚动这段segmentController将在其他单元格中

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

...在单元格2中选择其他索引(2)向下滚动,单元格5具有相同的选定索引,但我没有触摸它们

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       
    }
ios swift uitableview uisegmentedcontrol
2个回答
0
投票

UITableView和UICollectionView重用单元格。这意味着它只在内存中保留足够的单元格来显示屏幕上的内容。当您从屏幕上滚动细胞时,它们会被反馈回来,成为正在出现的细胞。您需要正确配置单元格,因为它们会重新出现在您的override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

因此,在您的情况下,您需要每次在cellForRow中设置分段控件的选择。

这意味着您需要一种方法来跟踪已对分段控件进行的选择,并在再次显示单元格时调用该方法以正确设置分段控件。


0
投票

通过子类化重置UITableViewCell的prepareForReuse方法中的选择。

override func prepareForReuse(){

}

© www.soinside.com 2019 - 2024. All rights reserved.