swift - 在搜索栏中使用搜索后如何保存复选标记?

标签 swift tableview uisearchbar checkmark

我正在尝试在 iOS 中创建一个搜索栏,并将其设置为过滤结果的位置,然后当您单击它时,它会显示一个复选标记。当我删除搜索文本时,复选标记消失并显示整页单元格,但我在搜索中选择的单元格未带有复选标记。这是通过 setSelected 方法在我的单元格中实现的:

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    
    if selected {
        accessoryType = .checkmark
    } else {
        accessoryType = .none
    }
}

我在 cellForRowAt 和 didSelectRowAt 方法中没有任何带复选标记的逻辑。

Here is a GIF of my problem

有人可以帮助我吗?

最佳答案

我假设您当前所做的只是在您的手机上设置复选标记。该单元格将被重复使用,您将失去复选标记。

您需要做的是跟踪项目,例如在 Set 中,用户到目前为止已检查过。在 TableView 中渲染项目时,您需要查询该集合是否选中该项目。如果是,您需要将复选标记添加到单元格中。

沿着这些思路,Item 是您的单元模型。这应该可以帮助您开始。您应该能够将其扩展到包含表标题组的数据集。

/// The items that have been checked.
var checkedItems = Set<Item>()

/// All items that are shown when no search has been performed.
var allItems: [Item]

/// The currently displayed items, which is the same as `allItems` in case no
/// search has been performed or a subset of `allItems` in case a search is
/// currently active.
var displayedItems: [Item]

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let item = displayedItems[indexPath.row]
    let cell = // Construct your cell as usual.

    if checkedItems.contains(item) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }

    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    let item = displayedItems[indexPath.row]

    if checkedItems.contains(item) {
        checkedItems.remove(item)
        cell.accessoryType = .none
    } else {
        checkedItems.insert(item)
        cell.accessoryType = .checkmark
    }
}

func updateSearchResults(for searchController: UISearchController) {
    displayedItems = // Set the displayed items based on the search text.
    tableView.scrollRectToVisible(.zero, animated: false)
    tableView.reloadData()
}

关于swift - 在搜索栏中使用搜索后如何保存复选标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55811050/

相关文章:

ios - 如何使用 updateHandler 初始化 HKObserverQuery?

ios - UITableViewCell 内的 UITextView 键盘问题

c++ - QT5中的TableView不显示MYSQL数据,只显示空行

ios - 自定义 UISearchBar 结果单元格

ios - 当手机处于横向模式时隐藏标签

ios - 当 View Controller 不是选定的选项卡或未显示时 NSTimer 停止

java - 更新 TableView 行外观

swift - 如何更新 TableView

iphone - 如何更改 iphone 中 UISearchBar 的 UiSearchbar 高度、宽度、颜色和 Uitextfield 高度?

ios - 更改UISearchBar中的CLEAR按钮的淡色颜色NOT CANCEL BUTTON