iOS 13中使用两类API设置TabBar自定义字体均遇Bug,如何解决?
iOS 13 UITabBar 自定义字体 Bug 解决方案
我之前在iOS 13开发时也踩过UITabBar自定义字体的这两个坑,不管是用UITabBarItem.appearance().setTitleTextAttributes还是tabBar.standardAppearance都会出问题,后来折腾出几个靠谱的解决办法,给你参考:
方案一:修复 setTitleTextAttributes 无效/异常问题
这个方法在iOS 13里的问题通常是字体设置不生效、切换Tab时样式错乱,核心原因是系统的样式优先级覆盖了自定义设置,你可以试试这两个调整:
- 延迟+针对性设置:在
viewDidAppear中重新设置(避免系统初始化时覆盖),同时确保覆盖normal和selected两种状态:
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let normalStyle: [NSAttributedString.Key: Any] = [ .font: UIFont(name: "YourCustomFont-Regular", size: 12)!, .foregroundColor: UIColor.darkGray ] let selectedStyle: [NSAttributedString.Key: Any] = [ .font: UIFont(name: "YourCustomFont-Bold", size: 12)!, .foregroundColor: UIColor.systemBlue ] UITabBarItem.appearance().setTitleTextAttributes(normalStyle, for: .normal) UITabBarItem.appearance().setTitleTextAttributes(selectedStyle, for: .selected) }
- 逐个Item设置替代全局Appearance:全局Appearance有时候会被系统局部样式覆盖,直接遍历TabBar的items逐个设置更可靠:
for item in tabBar.items ?? [] { item.setTitleTextAttributes(normalStyle, for: .normal) item.setTitleTextAttributes(selectedStyle, for: .selected) }
方案二:修复 standardAppearance 字体不生效问题
用standardAppearance时的Bug大多是漏配置了不同布局模式下的样式(iOS 13+ TabBar有多种布局状态),必须把所有布局对应的样式都设置完整:
let appearance = UITabBarAppearance() // 配置堆叠布局(手机竖屏常用) appearance.stackedLayoutAppearance.normal.titleTextAttributes = normalStyle appearance.stackedLayoutAppearance.selected.titleTextAttributes = selectedStyle // 配置内联布局(iPad横屏/大屏设备常用) appearance.inlineLayoutAppearance.normal.titleTextAttributes = normalStyle appearance.inlineLayoutAppearance.selected.titleTextAttributes = selectedStyle // 配置紧凑内联布局(部分特殊场景) appearance.compactInlineLayoutAppearance.normal.titleTextAttributes = normalStyle appearance.compactInlineLayoutAppearance.selected.titleTextAttributes = selectedStyle // 应用样式,同时注意iOS 15+要额外设置scrollEdgeAppearance避免滚动时样式重置 tabBar.standardAppearance = appearance if #available(iOS 15.0, *) { tabBar.scrollEdgeAppearance = appearance }
额外避坑提示
- 先确认自定义字体已经正确添加到项目,并且在
Info.plist的Fonts provided by application中注册了完整的字体文件名(包括后缀) - 如果还是有问题,可以在
application(_:didFinishLaunchingWithOptions:)里先做一次全局设置,再在TabBarController的viewDidLoad中重复设置一次,双重保险避免系统样式覆盖
内容的提问来源于stack exchange,提问作者Alex Shoshiashvili
相关产品推荐
相关产品推荐

