You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置UITabBarAppearance且不覆盖UITabBarItem.appearance的全局样式配置

问题原因

iOS 13起苹果推出了基于UIBarAppearance的新一代导航栏、标签栏外观API,iOS 15新增的scrollEdgeAppearance属性优先级远高于旧版全局UITabBarItem.appearance()配置。你创建的全新UITabBarAppearance实例默认使用系统自带的标题样式,赋值给tabBar后会直接覆盖之前的全局自定义字体配置。

解决方案

根据你的适配需求可以选择以下两种实现方式:

方案1:全局统一配置(适合App内所有UITabBar样式一致的场景)

直接对UITabBarAppearance做全局配置,同时适配不同系统版本,避免新旧API冲突:

if #available(iOS 15.0, *) {
    let appearance = UITabBarAppearance()
    appearance.configureWithDefaultBackground()
    // 配置所有布局状态下的标题样式,覆盖横竖屏、iPad等场景
    let normalAttrs = TextStyle.tabTitle(colored: false).attributes
    let selectedAttrs = TextStyle.tabTitle(colored: true).attributes
    appearance.stackedLayoutItem.setTitleTextAttributes(normalAttrs, for: .normal)
    appearance.stackedLayoutItem.setTitleTextAttributes(selectedAttrs, for: .selected)
    appearance.inlineLayoutItem.setTitleTextAttributes(normalAttrs, for: .normal)
    appearance.inlineLayoutItem.setTitleTextAttributes(selectedAttrs, for: .selected)
    appearance.compactInlineLayoutItem.setTitleTextAttributes(normalAttrs, for: .normal)
    appearance.compactInlineLayoutItem.setTitleTextAttributes(selectedAttrs, for: .selected)
    // 全局生效
    UITabBar.appearance().standardAppearance = appearance
    UITabBar.appearance().scrollEdgeAppearance = appearance
} else {
    // iOS15以下沿用旧版全局配置
    UITabBarItem.appearance().setTitleTextAttributes(TextStyle.tabTitle(colored: false).attributes, for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes(TextStyle.tabTitle(colored: true).attributes, for: .selected)
}

方案2:单个UITabBar实例配置(适合仅部分页面需要修改标签栏样式的场景)

在你原有配置scrollEdgeAppearance的代码中,补充当前UITabBarAppearance实例的标题样式即可:

let appearance = UITabBarAppearance()
appearance.configureWithDefaultBackground()
// 补充当前实例的标题样式配置
let normalAttrs = TextStyle.tabTitle(colored: false).attributes
let selectedAttrs = TextStyle.tabTitle(colored: true).attributes
appearance.stackedLayoutItem.setTitleTextAttributes(normalAttrs, for: .normal)
appearance.stackedLayoutItem.setTitleTextAttributes(selectedAttrs, for: .selected)
// 按需补充横竖屏、iPad适配的布局配置
// appearance.inlineLayoutItem...
// appearance.compactInlineLayoutItem...

tabBar.standardAppearance = appearance
tabBar.scrollEdgeAppearance = appearance
注意事项
  • 不要同时混用旧版UITabBarItem.appearance()配置和新版UITabBarAppearance配置,iOS15+会优先读取后者的样式,旧配置会完全失效。
  • 三种布局类型stackedLayoutItem(常规竖屏堆叠布局)、inlineLayoutItem(iPad横屏内嵌布局)、compactInlineLayoutItem(小屏横屏紧凑布局)按需配置,避免横竖屏切换时样式异常。

内容的提问来源于stack exchange,提问作者James White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:09:02