Swift - 控制在自定义 tableviewcell 中显示的内容

Swift - Controlling what is displayed in a custom tableviewcell

我有一个自定义单元格,它有一个包含多个按钮的堆栈视图。我需要能够根据数据项显示每个按钮。例如,在一个单元格中会出现三个按钮,在另一个单元格中会出现 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
}

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

如何控制显示哪些按钮?

您可以使用 ctrl+拖动来创建一个 Outlet Collection,它是一组按钮,而不是 ctrl+拖动来创建一个 outlet。现在您可以在 for 循环中访问它们。

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

出于某种原因,界面生成器不保证数组中按钮的顺序,因此在 awakeFromNib 中按 x 顺序对数组进行排序:

cell.buttons.sort {[=11=].0.frame.origin.x < [=11=].1.frame.origin.x }