【问题标题】:Add legend under Custom Cell in Table View with Swift使用 Swift 在表格视图中的自定义单元格下添加图例
【发布时间】:2018-01-24 05:22:09
【问题描述】:

我目前正在尝试复制您在图片中看到的数组:

我创建了一个自定义单元格类,以便显示标签和切换按钮。我不知道的部分是如何在每个单元格下方显示图例。

这是我目前的代码:

 var options = ["Solstice", "Equinox", "Enable Snapshot"]

 public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return options.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
    let switchView = UISwitch(frame: CGRect.zero)
    cell.addSubview(switchView)
    cell.accessoryView = switchView
    cell.nameLabel.text = options[indexPath.row]
    return cell
}

图例可以是另一个自定义单元格,具有不同的样式吗?最好的方法是什么?

【问题讨论】:

  • 使用两个表格视图单元格,一个用于带有开关的标签,另一个单元格是您的文本,并将其显示为奇偶数,或者您也可以根据您的显示要求执行条件代码。
  • cell.addSubview(switchView) 不,这是个坏主意。导致重用问题以及将其设置为accessoryView

标签: ios swift uitableview


【解决方案1】:

使用分组样式而不是普通样式设置您的表格视图。将每一行放在自己的部分中。

为每个图例使用节页脚标题。这是通过func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? 数据源方法完成的。

【讨论】:

  • 对于@rmaddy 的回答,我建议你看看developer.apple.com/documentation/uikit/uitableviewdelegate/…
  • @Samah 实际上所需的方法是 UITableViewDataSource 的一部分。
  • 我忘了titleForFooterInSection。如果你想要一个完全自定义的视图,你需要UITableViewDelegate
  • 好的,我使用分组表viewForFooterInSectionheightForFooterInSection 解决了这个问题。谢谢大家!
  • 您可以只使用titleForFooterInSection 而不是其他两个,除非您想要的图例不仅仅是简单的文本。
【解决方案2】:

有两种选择:-

1)

  var options = [ {"title":"Solstice", "description" :"legend" }, {"title":"Equinox", "description" :"legend"} , {"title":"Enable Snapshot", "description" :"legend"}]

然后,您可以在同一单元格中创建标签、开关和图例。对于图例中的标签,应该给定行数 0,并且没有恒定的高度,以便标签根据类似于AutoLayout to dynamically size UILabel Height and Width的文本增加高度

2) 创建视图,将 switch 作为部分标题,将图例作为每个标题内的行 // 这通常在每个部分有多行时使用,因为您的用例只有一行(图例),使用单细胞会更容易实现

【讨论】:

  • 3) 使用 Apple 为此目的提供的功能tableView(_:, titleForFooterInSection)
猜你喜欢
  • 2014-11-17
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多