How to hide a section in UITableView?

前端 未结 12 2225
梦如初夏
梦如初夏 2020-12-05 00:32

There are some section in the table that does not contain any data and would like to hide that section.

How to do this?

12条回答
  •  感动是毒
    2020-12-05 01:16

    For the case of static table, that is, the table sections and cells are configured in Storyboard. The following are my strategies to hide a specified section depending conditions.

    Step one: implement two func defined in UITableViewDelegate - heightForRowAt - heightForHeaderInSection

    For example, here are swift codes:

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
    {
       // if indexPath contains the specified section AND
       //    the condition for hiding this section is `true`
       //       return CGFloat(0)
       // else 
       //    return super.tableView(tableView, heightForRowAt: indexPath)
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat 
    {
       // similar logic to set header height
    }
    

    Step two: define a func to set cells hidden for specific section and call it from viewWillAppear:

    private func setSectionVisible()
    {
       /*
       if condition for visible is true
          let index = IndexPath(row:..., section:...)
          let cell = self.tableView.cellForRow(at: index)
          cell.isHiden = true
       */
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setSectionVisible()
    }
    

    In case you need to reload tableview, you may need to call setSectionVisible() again.

    I think this strategy may work for dynamic data from DataSource. In this way, you can control when to make specific section visible or hidden.

提交回复
热议问题