Swift:如何将单元格发送到TableView的正确部分?

时间:2019-02-23 22:00:04

标签: swift uitableview tableview

我有简单的TableView和唯一的自定义单元格。 根据某些布尔,我需要:
1.如果bool为true,则在第0节中显示单元格;
2.如果bool为假,则在第1节中显示单元格。

找不到正确的方法,需要帮助。 谢谢!

1 个答案:

答案 0 :(得分:0)

这可以通过在表视图的数据源中实现适当的逻辑并在布尔值更改时在表视图上调用适当的更新方法来实现。

基本示例:

var showSomethingInSectionZero = true

func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

func numberOfRows(inSection section: Int) -> Int {
    if section == 0, showSomethingInSectionZero {
        return 1
    } else if section == 1, !showSomethingInSectionZero {
        return 1
    }
    return 0
}

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

并更新布尔视图和表视图:

showSomethingInSectionZero = false
tableView.reloadData()

或者将其设置为动画:

showSomethingInSectionZero = false
tableView.moveRow(at: IndexPath(row: 0, section: 0), 
      to: IndexPath(row: 0, section: 1))

这是它的基础,如果您想要更深入的答案,则应提供更多上下文和代码。