【问题标题】:UITableview with 2 Sections Selection带有 2 个部分选择的 UITableview
【发布时间】:2020-03-04 17:45:34
【问题描述】:

我的 UITableview 有 2 个部分,每个部分有行数,我想允许在 tableview 中进行多项选择,但每个部分应该只有 1 行。

换句话说,“我想在整个表格视图中允许 2 个选择,在每个部分中允许 1 个选择”

任何可以提供帮助的人将不胜感激。 提前致谢

【问题讨论】:

  • 使用tableView(_:willSelectRowAt:) 允许或不允许选择是否在同一部分中已经选择了另一个,或者取消选择该部分中的前一个?

标签: ios swift uitableview


【解决方案1】:

您可以通过以下自定义实现实现相同的效果

定义 2 元素数组以保存每个部分的 uniq 选择

var selection = [-1, -1]

处理用户选择的自定义方法

func setSelection(for index: IndexPath) {
    if selection[index.section] != -1 {
      //clear the old selection
      let cell = getCell(for: IndexPath(row: selection[index.section], section: index.section))
      cell.backgroundColor = .white
    }
    //add new selectoin
    let currCell = getCell(for: index)
    currCell.backgroundColor = .orange

    //save new selection state
    selection[index.section] = index.row
  }

func getCell(for index: IndexPath) -> UITableViewCell {
    let cell = custTableView.cellForRow(at: index)
    return cell!
  }

setSelection 需要从didSelectRowAt 调用

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

您也可以随时使用selection 数组来了解选定的单元格索引

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多