ios - 具有单选和多选的uitableview

标签 ios swift uitableview

我有一个包含三个部分的 TableView 。

第 0、1 节:选择该节中的一行。选定的行得到一个复选标记。如果选择了新行,请取消选择并取消选中旧选择。

第 2 部分:在此部分中按一个可自动转场。


问题是当我按下第 2 部分中的一行时,会出现一个复选标记,然后它会继续。我根本不希望复选标记出现,但我很难找到摆脱它的方法。

我在 viewDidLoad 中设置了 self.tableView.allowsMultipleSelection = true,这样我就可以在每个部分中选择一行,这对前两个部分非常有用。

然后在 cellForRowAt 中,我为第 2 部分(第三部分)设置了 cell.accessoryType = .none,这样我就不会在选择行时得到复选标记部分。

不过好像不行。


override func viewDidLoad() {
    self.tableView.allowsMultipleSelection = true
}

override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let section = indexPath.section
    switch section {
    case 0,1:
        if let selected = tableView.indexPathsForSelectedRows {
            for selectedIndexPath in selected {
                if selectedIndexPath.section == indexPath.section {
                    tableView.deselectRow(at: selectedIndexPath, animated: false)
                }
            }
        }
        return indexPath
    case 2:
        return indexPath
    default:
        return nil
    }
}



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FilterTableViewCell", for: indexPath) as! FilterTableViewCell
    let section = indexPath.section
    switch section {
    case 0:
        cell.theLabel.text = myDataStuff[indexPath.row]
    case 1:
        cell.theLabel.text = otherDataStuff[indexPath.row]
    case 2:
        cell.theLabel.text = lastDataStuff[indexPath.row]
        cell.accessoryType = .none
    default:
        break
    }
    return cell
}

最佳答案

你的类 FilterTableViewCell 中可能有这样的东西(也许下次分享更多代码):

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

因此,即使您在第 3 部分中的行具有 accessoryType = .none,当您选择它们​​时,此属性会再次修改。

快速的解决方案是使用这些函数来处理复选标记而不是 setSelected:

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

}

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

}

关于ios - 具有单选和多选的uitableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53565812/

相关文章:

ios - 快速从 FB 获取用户信息

ios - 如何通过按下按钮删除动画。 swift

ios - KDCircularProgressView 不显示

ios - 快速在具有动态宽度的 UIView 中添加 UIButtons

ios5 - 使用 Storyboard 自定义 UITableViewCell

iOS - UITableView 显示错误的单元格星数

android - 使用 React Native 时,我有哪些存储数据的选项? (iOS 和安卓)

iphone - 如何处理通讯录变更

ios - 使用 switch 语句创建泛型函数,该函数根据传入参数的类型执行不同的代码

ios - 使用 tableViewCells 进行 Segue