Swift UITableView如何同时使用自定义和默认Section Header
解决方案
核心逻辑:在不需要自定义header的section分支直接返回nil即可,系统会自动生成标准的默认section header视图。
代码修正
你现有代码存在多余的视图添加操作,self.view.addSubview(viewDimensionHeader)不需要手动调用,UITableView会自动管理返回的header视图的层级,修正后完整代码如下:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 1 { return viewDimensionHeader // 自定义header正常返回 } else { return nil // 返回nil触发系统默认header渲染 } }
补充注意事项
- 如果你需要默认header展示指定文字,实现
tableView(_:titleForHeaderInSection:)数据源方法,给对应section返回标题即可,系统会自动将文字渲染到默认header上。 - 如果你同时实现了
tableView(_:heightForHeaderInSection:)代理方法,非自定义header的section请返回UITableView.automaticDimension,即可保留系统默认header的标准高度,无需手动计算。
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 1 { return 80 // 自定义header的高度,按你的实际需求修改 } else { return UITableView.automaticDimension // 系统默认header高度 } }
内容的提问来源于stack exchange,提问作者zootzoot
相关产品推荐
相关产品推荐

