gpt4 book ai didi

ios - 如何以编程方式在 iOS 中的多选 UITableView 中预选单元格

转载 作者:行者123 更新时间:2023-12-04 07:24:16 25 4
gpt4 key购买 nike

我使用 UITableView让用户从多个给定选项中进行选择,并允许进行多项选择。我还希望用户稍后返回此 View 并更改先前所做的选择,这意味着我必须能够使用先前的选择加载和初始化表。此外,用户可以点击“全选”按钮,该按钮应该以编程方式设置所有选项。
为此,我有一组 bool 值来跟踪已检查和未检查的项目。但是,为了正确触发didSelectRowAtdidDeselectRowAt事件, TableView 也需要知道选择状态。所以我想出了两个选项,我都不完全满意:
使用我自己的数组设置单元配件类型:

func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
cell.textLabel!.text = items[indexPath.row].name
if items[indexPath.row].isSelected {
cell!.accessoryType = .checkmark
} else {
cell!.accessoryType = .none
}
return cell
}

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

let cell = tableView.cellForRow(at: indexPath)
cell!.accessoryType = .checkmark
...
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell!.accessoryType = .none
...
}
这很好地切换了状态并更新了支持数组。它没有做的是让表格 View 知道每个单元格的选择状态。因此,在重新加载时,会触发错误的选择事件(选择/取消选择),然后要求用户最初点击两次以更改状态。现在我可以通过处理 didSelectRowAt 中的两种状态来解决这个问题。和 didDeselectRowAt但它与控件的状态相矛盾,并可能在以后导致问题。

让表格 View 跟踪状态:
在这里,我换了
if isSelected(index: indexPath.row) {
if let selectedRows = tableView.indexPathsForSelectedRows, selectedRows.contains(indexPath) {
这使表格 View 在内部保持更新,但是当用户返回带有一些预选项目的表格或单击“全选”时,我还没有找到一种以编程方式设置状态的好方法。尝试遍历我的数组并使用例如设置选择
`tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)`
(如对类似问题的回答中所建议的)在适用的情况下并没有导致预期的结果。
用预先选择的值初始化我的表并在单击“全选”时更新它的最佳方法是什么?

最佳答案

您应该完全使用您的数据模型来管理它。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)

// Assumption: item is a class, so changes are reflected in array as expected
let item = items[indexPath.row]
item.isSelected.toggle()

cell!.accessoryType = item.isSelected ? .checkmark : .none
}
这样,您的数据模型始终只有一个事实来源。您的 tableView 实例不需要为您记住任何内容,它由您提供的数据驱动。
如果你这样走,你不需要执行 didDeselect委托(delegate)方法或设置 allowsMultipleSelectiontrue .

关于ios - 如何以编程方式在 iOS 中的多选 UITableView 中预选单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68305790/

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