【问题标题】:Swift UITableView with Custom Cell and Multiple Sections array data具有自定义单元格和多节数组数据的 Swift UITableView
【发布时间】:2019-08-01 09:09:28
【问题描述】:

我的场景,我正在尝试使用自定义单元格和来自单个数组的多个部分创建 UITableView。在这里,我需要在部分中显示不同的标题。这该怎么做?我使用了下面的代码,但无法清楚地理解。

下面是我的代码

var  data = [["1","2","3"], ["4","5"]]
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return data.count
}

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 20
} 

【问题讨论】:

  • 你应该实现 UITableViewDelegate 和 UITableViewDataSource 方法
  • @dahiya_boy 我的场景我要求单个数组添加数据部分和行
  • 每个部分的标题应该是什么?
  • @PGDev 我需要给出一些字符串标题。到目前为止,您可以提供一些示例数据。将来我会将 JSON 数据加载到其中。截至目前模拟数据足够

标签: ios swift uitableview


【解决方案1】:

周围可以有2个案例,

  1. 如果您只想为每个 section 添加 String 标题,请实现 UITableViewDataSource's tableView(_: titleForHeaderInSection:) 方法。

  2. 如果您想为每个section 提供一个自定义view,请实现UITableViewDelegate's tableView(_:viewForHeaderInSection:) 方法。

这是tableView(_: titleForHeaderInSection:) 的示例,

class VC: UIViewController, UITableViewDataSource {
    let data = [["1","2","3"], ["4","5"]]
    let sectionNames = ["This is Sec-1", "And this is Sec-2"]

    func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data[section].count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
        cell.textLabel?.text = data[indexPath.section][indexPath.row]
        return cell
    }

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

如果您需要为每个section 自定义高度,请实现tableView(_:heightForHeaderInSection:)

截图:

编辑:

使用accessoryType 作为.checkmark 进行单元格选择。

像这样创建一个自定义的UITableViewCelloverride setSelected(_:animated:) 方法,

class CustomCell: UITableViewCell {
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.accessoryType = selected ? .checkmark : .none
    }
}

xib中的CustomCellreuseIdentifier设置为cell。此外,更新tableView(_:cellForRowAt:) 方法以使CustomCell 实例出列。我在上面的代码中更新了它。

【讨论】:

  • 超级。在这里,我有一个疑问,如果我想将自定义数据加载到部分中。怎么做?在同一个数组中而不是计数如何获取自定义数据?
  • 使用 titleForHeaderInSection 方法中的 section 参数获取自定义部分名称。我已经更新了答案以向您展示示例。
  • 对不起,您能否在答案中添加复选标记。复选标记应一次选择一个单元格。
  • 这是一个单独的要求。您应该为此提出一个单独的问题。
  • 更新了答案。享受..?
猜你喜欢
  • 2018-06-24
  • 2018-01-06
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多