Swift:UITableView分区标题样式设置疑问
不用自定义View!快速调用iOS系统标准分区表头样式
刚好我之前也踩过类似的坑——不想自己写viewForHeaderInSection造轮子,又要拿到系统偏好设置里那种大写、小字号、底部对齐的分区标题?其实iOS本身就给你留了后门,直接复用系统默认的表头视图就行,几步就能搞定:
步骤1:用系统默认方法返回标题
先别着急写自定义视图,老老实实在代理里用titleForHeaderInSection返回你的分区标题:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // 返回对应分区的标题,比如按section索引取数组里的内容 return sectionTitles[section] }
步骤2:在willDisplayHeaderView里修改样式
系统会自动帮你创建UITableViewHeaderFooterView,你只需要在它显示前调整属性就行,这才是最省事的方法:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { guard let headerView = view as? UITableViewHeaderFooterView else { return } // 1. 转成大写(完全匹配系统样式) headerView.textLabel?.text = headerView.textLabel?.text?.uppercased() // 2. 设置小字号,用系统原生的caption1样式适配动态类型,或者指定固定大小 // 适配动态类型推荐这个: headerView.textLabel?.font = UIFont.preferredFont(forTextStyle: .caption1, compatibleWith: .none) // 或者固定大小(比如系统偏好里的12号字): // headerView.textLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium) // 3. 底部对齐:调整textLabel的位置,让它贴表头底部 headerView.textLabel?.frame = CGRect( x: 16, // 左边距和系统保持一致 y: headerView.bounds.height - 20, // 距离底部4px左右,自己微调 width: headerView.bounds.width - 32, height: 16 ) // 额外:如果需要调整表头高度,在heightForHeaderInSection里设置 // func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // return 30 // 比默认高度矮一点,更贴合系统样式 // } }
进阶:全局统一设置所有TableView的表头样式
如果你想让APP里所有的TableView都用这个样式,不用每个页面都写代理方法,可以在APP启动时全局配置:
// 在AppDelegate的didFinishLaunchingWithOptions里,或者SceneDelegate的sceneDidBecomeActive里 UITableViewHeaderFooterView.appearance().textLabel?.font = UIFont.preferredFont(forTextStyle: .caption1) // 大写可以统一在返回标题时处理,或者用attributedString
这样一来,你完全复用了系统的表头视图,既不用自己写布局,又完美匹配系统偏好设置里的样式,完全符合你“不重复造轮子”的需求!
内容的提问来源于stack exchange,提问作者iphaaw
相关产品推荐
相关产品推荐

