How to hide first section header in UITableView (grouped style)

前端 未结 15 797
[愿得一人]
[愿得一人] 2020-12-07 11:15

As the design of table views using the grouped style changed considerably with iOS 7, I would like to hide (or remove) the first section header. So far I haven\'t managed to

相关标签:
15条回答
  • 2020-12-07 11:49

    The following worked for me in with iOS 13.6 and Xcode 11.6 with a UITableViewController that was embedded in a UINavigationController:

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        nil
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        .zero
    }
    

    No other trickery needed. The override keywords aren't needed when not using a UITableViewController (i.e. when just implemented the UITableViewDelegate methods). Of course if the goal was to hide just the first section's header, then this logic could be wrapped in a conditional as such:

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            return nil
        } else {
            // Return some other view...
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return .zero
        } else {
            // Return some other height...
        }
    }
    
    0 讨论(0)
  • 2020-12-07 11:50

    I can't comment yet but thought I'd add that if you have a UISearchController on your controller with UISearchBar as your tableHeaderView, setting the height of the first section as 0 in heightForHeaderInSection does indeed work.

    I use self.tableView.contentOffset = CGPointMake(0, self.searchController.searchBar.frame.size.height); so that the search bar is hidden by default.

    Result is that there is no header for the first section, and scrolling down will show the search bar right above the first row.

    0 讨论(0)
  • 2020-12-07 11:51

    Try this if you want to remove all section header completely

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    0 讨论(0)
提交回复
热议问题