swift 3 中不同部分的表视图中执行互斥选择的最佳方法

Best way to perform mutually exclusive selection in a tableview in different sections in swift 3

我有一个包含不同部分的表视图,我需要能够从不同的部分进行多select,但每个部分中的行应该能够select 明智地相互排斥。例如:在下面的屏幕截图中,我应该能够 select 来自比萨的玛格丽塔或烧烤鸡肉,对于深盘比萨也是如此,但我应该能够在比萨区和深盘比萨之间 select

下面是我到目前为止的代码,我想知道什么是解决这个问题的最佳方法。

   let section = ["Pizza", "Deep dish pizza"]

    let items = [["Margarita", "BBQ Chicken"], ["Sausage", "meat lovers"]]

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.section[section]
    }



    override func numberOfSections(in tableView: UITableView) -> Int {

        return section.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return items[section].count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        // Configure the cell...

        cell.textLabel?.text = items[indexPath.section][indexPath.row]

        return cell
    }

首先允许多个selection:

yourTableView.allowsMultipleSelection = true

要获取 select 行:

let selectedRows = tableView.indexPathsForSelectedRows

然后在 didselectrow 函数中,您可以遍历 selected 行并确保该部分中只有 1 行可以 selected。

好的,所以我想通了,我创建了一个循环并检查所有行的方法,并在 tableview didselect 和 deselect 中调用了它

func updateTableViewSelections(selectedIndex:IndexPath)
    {

        for  i in 0  ..< tableView.numberOfSections
        {
            for k in 0  ..< tableView.numberOfRows(inSection: i)
            {

                if let cell = tableView.cellForRow(at: IndexPath(row: k, section: i))

                {

                    if sections.getType(index: i) == selectedIndex.section
                    {
                        if (selectedIndex.row == k && cell.isSelected)
                        {
                            cell.setSelected(cell.isSelected, animated: false)
                        }
                        else
                        {
                            cell.setSelected(false, animated: false)
                        }
                    }
                }


            }
        }


    }

您应该创建一些数据元素来跟踪每一行的选择。

我建议使用 [Int:Int] 的字典,其中键是节,值是行。

选择一行后,您可以轻松检查该部分中是否已选择另一行,并在需要时取消选择。

var rowSelections = [Int:Int]()

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let section = indexPath.section
        if let row = self.rowSelections[section] {
            tableView.deselectRow(at: IndexPath(row:row, section:section), animated: true)
        }
        self.rowSelections[section]=indexPath.row
    }

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let section = indexPath.section
    self.rowSelections[section]=nil
}