gpt4 book ai didi

ios - UITableViewCell 无意中在不需要的行上放置了复选标记

转载 作者:行者123 更新时间:2023-11-28 15:02:30 26 4
gpt4 key购买 nike

我正在制作一个音乐流派选择应用程序,当我去我的 table 选择流派时,我选择了一行,它从我的选择中随机选择了大约 10 行。

我的选择代码是:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let genresFromLibrary = genrequery.collections
let rowitem = genresFromLibrary![indexPath.row].representativeItem
print(rowitem?.value(forProperty: MPMediaItemPropertyGenre) as! String
)
if let cell = tableView.cellForRow(at: indexPath)
{
cell.accessoryType = .checkmark
}
}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath)
{
cell.accessoryType = .none
}
}

最佳答案

调用 cellForRowAtIndexPath 时,默认情况下会重用单元格。当您不跟踪已选择的 indexPaths 时,这会导致单元格包含错误数据。您需要跟踪当前选择的索引路径,以便您可以在表格 View 中显示适当的附件类型。

一种方法是在您的 UITableViewController 中设置一个属性,该属性仅存储所选单元格的索引路径。它可以是一个数组或一个集合。

var selectedIndexPaths = Set<IndexPath>()

当您在 didSelectRowAt 上选择一行时,从 selectedIndexPaths 中添加或删除单元格,具体取决于索引路径是否已在数组中:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedIndexPaths.contains(indexPath) {
// The index path is already in the array, so remove it.
selectedIndexPaths.remove(indexPathIndex)
} else {
// The index path is not part of the array
selectedIndexPaths.append(indexPath)
}

// Show the changes in the selected cell (otherwise you wouldn't see the checkmark or lack thereof until cellForRowAt got called again for this cell).
tableView.reloadRows(at: [indexPath], with: .none)
}

完成后,在您的 cellForRowAtIndexPath 上,检查 indexPath 是否在 selectedIndexPaths 数组中以选择 accessoryType

if selectedIndexPaths.contains(indexPath) {
// Cell is selected
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}

这应该可以解决每 10 个单元格左右检查一次看似随机的单元格的问题(这不是随机的,只是带有复选标记的单元格被重复使用)。

关于ios - UITableViewCell 无意中在不需要的行上放置了复选标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48758502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com