【问题标题】:Swift - Controlling what is displayed in a custom tableviewcellSwift - 控制自定义 tableviewcell 中显示的内容
【发布时间】:2017-01-25 01:48:41
【问题描述】:

我有一个自定义单元格,它有一个包含多个按钮的堆栈视图。我需要能够根据数据项显示每个按钮。例如,在一个单元格中会出现三个按钮,在另外一个单元格中会出现 4 个不同的按钮,在另一个单元格中会出现所有按钮。单元格如下所示:

作为测试,我尝试了下面的代码来设置按钮:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "doctrineCell", for: indexPath) as! DoctrineCell

    let doctrine = doctrines[indexPath.row]
    cell.doctrineLabel.text = doctrine.doctrineText!

    cell.bofmButton.isHidden = true
    cell.otButton.isHidden = true
    cell.ntButton.isHidden = true
    cell.ldaButton.isHidden = true
    cell.ldpButton.isHidden = true
    cell.pbutton.isHidden = true
    cell.jsbutton.isHidden = true
    cell.allButton.isHidden = true

    cell.ldaButton.isHidden = false
    cell.ldpButton.isHidden = false
    cell.pbutton.isHidden = false    

    return cell
}

当我运行应用程序时,所有按钮都会显示。

如何控制显示哪些按钮?

【问题讨论】:

  • 您确定所有的插座都设置正确了吗?
  • 请显示DoctrineCell的定义。
  • 哦,还有一件非常重要的事情:在任何代码上放置一个断点并确保它甚至正在运行。有一个非常现实的可能性,如果你设置错误,它永远不会运行,所以让我们消除它。
  • 上面的代码没有问题。问题可能在于如何创建单元格和/或如何为这些按钮建立插座。或者,如果这些按钮是一些特殊的自定义子类,那么该代码可能存在问题。但问题不在于cellForRowAt 代码...
  • 感谢问题出在网点...感谢您的帮助

标签: ios swift uitableview tableviewcell uistackview


【解决方案1】:

您可以通过 ctrl+拖动来创建一个 Outlet 集合,而不是 ctrl+拖动来创建一个插座,它是一组按钮。现在您可以在 for 循环中访问它们。

cell.buttons.forEach {$0.isHidden = true}
cell.buttons[8].isHidden = false
cell.buttons[9].isHidden = false
cell.buttons[10].isHidden = false

无论出于何种原因,界面构建器都不保证数组中按钮的顺序,因此在 awakeFromNib 中按 x 顺序对数组进行排序:

cell.buttons.sort {$0.0.frame.origin.x < $0.1.frame.origin.x }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多