Swift3 iOS中如何显示和隐藏UITableView自定义表头单元格
哦,我明白你的问题了——你混淆了tableView的全局表头(tableHeaderView)和section的表头!你现在用tableView(_:viewForHeaderInSection:)设置的是section级别的表头,而tableView.tableHeaderView?.isHidden = true操作的是整个tableView最顶部的那个全局表头,这俩完全不是一回事,所以那行代码当然没用啦。
正确的做法确实要在heightForHeaderInSection里做判断,同时配合viewForHeaderInSection来控制是否返回表头视图。具体步骤如下:
- 先定义一个布尔变量来标记是否要显示section表头,根据你的用户逻辑动态赋值:
var shouldShowSectionHeader = true // 比如普通用户设为false,VIP用户设为true
- 修改
heightForHeaderInSection方法,根据变量返回对应高度:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // 需要显示就返回设定的235.0,不需要就返回0 return shouldShowSectionHeader ? 235.0 : 0.0 }
- 同步调整
viewForHeaderInSection方法,避免不必要的cell创建:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard shouldShowSectionHeader else { return nil // 不返回表头视图 } let headerCell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! CustomHeaderCell // 这里还可以根据用户类型配置headerCell的内容,比如不同用户显示不同信息 return headerCell }
- 如果需要在运行时动态切换显示状态(比如用户登录后更新权限),修改
shouldShowSectionHeader的值后,记得刷新对应的section:
// 假设刷新第0个section,根据你的实际section索引调整 tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
这样就能完美实现根据不同用户显示或隐藏section表头的需求啦。
内容的提问来源于stack exchange,提问作者user2786
相关产品推荐
相关产品推荐

