繁体   English   中英

如何使用 Swift 将多个单元格选择转换为单个单元格选择

[英]How to convert multiple cell selection to single cell selection using Swift

在我的场景中,我试图一次创建单个单元格选择复选checkmark 我使用下面的代码进行多个单元格选择,并使用isSelected Bool 值来选择单元格持久化。 现在,如何将以下代码转换为单个单元格selection

我的代码如下

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    let item = self.titleData[indexPath.row]
    cell.textLabel?.text = item.title
    cell.accessoryType = item.isSelected ? .checkmark : .none
    return cell
}

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        titleData[indexPath.row].isSelected.toggle()
        tableView.reloadRows(at: [indexPath], with: .none)
        let selectedTitle = titleData.filter{$0.isSelected}
        print("\(selectedTitle)")
    }

首先,在 viewDidLoad() 中,让你的 tableView 只允许单选。 像这样:

yourTableView.allowsMultipleSelection = false 

那么您可以为此使用didSelectRowAtdidDeselectRowAt 这将一次只启用一个选择。

// assign isSelected true and accessoryType to checkmark

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    self.titleData[indexPath.row].isSelected = true
    let selectedTitle = self.titleData[indexPath.row].title
    cell.accessoryType = .checkmark

}

// assign isSelected false and accessoryType to none

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    self.titleData[indexPath.row].isSelected = false
    cell.accessoryType = .none
}

您需要维护全局变量,因为如果您想使用数组进行管理,则需要在每次进行选择之前重置数组的 isSelected 位。

var isSelected = false
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        let item = self.titleData[indexPath.row]
        cell.textLabel?.text = item.title
        cell.accessoryType = isSelected ? .checkmark : .none
        return cell
     }
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

         isSelected = true
        tableView.reloadData()

     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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