如何创建并初始化自定义UITabBarItem类以统一标签栏样式
自定义UITabBarItem实现统一样式
这个需求很常见,用自定义子类来统一TabBarItem样式确实是最优解,不用在每个VC里重复写代码。我帮你把这个类补全,保证不管是代码创建还是用Storyboard/XIB拖的TabBarItem,都能自动应用统一样式。
完整的CustomTabBarItem实现
import UIKit class CustomTabBarItem: UITabBarItem { // 统一配置样式的私有方法,只在内部调用 private func customiseTabBarItems() { // 普通状态下的文本属性,替换成你需要的字体和颜色 let normalTextAttributes: [NSAttributedString.Key: Any] = [ .font: Fonts.small!, // 用你自己定义的Fonts.small .foregroundColor: UIColor.systemGray ] // 选中状态下的文本属性,可单独调整字体粗细或颜色 let selectedTextAttributes: [NSAttributedString.Key: Any] = [ .font: Fonts.small!, // 也可以换成稍粗的字体增强区分度 .foregroundColor: UIColor.systemBlue ] // 给不同状态设置文本属性 setTitleTextAttributes(normalTextAttributes, for: .normal) setTitleTextAttributes(selectedTextAttributes, for: .selected) // 可选:设置图片渲染模式,让图片颜色和文本颜色统一(继承tintColor) image = image?.withRenderingMode(.alwaysTemplate) selectedImage = selectedImage?.withRenderingMode(.alwaysTemplate) } // 重写默认初始化方法 override init() { super.init() customiseTabBarItems() } // 重写带标题、普通图、选中图的初始化方法 init(title: String?, image: UIImage?, selectedImage: UIImage?) { super.init(title: title, image: image, selectedImage: selectedImage) customiseTabBarItems() } // 重写带标题、图、标签的初始化方法 init(title: String?, image: UIImage?, tag: Int) { super.init(title: title, image: image, tag: tag) customiseTabBarItems() } // 处理Storyboard/XIB加载的情况(必须实现这个初始化器) required init?(coder: NSCoder) { super.init(coder: coder) customiseTabBarItems() } }
关键细节说明
- 覆盖所有初始化器:不管你是用代码直接创建,还是在Storyboard里拖的TabBarItem,都会触发样式配置,确保没有遗漏场景。
- 私有样式方法:把样式配置封装成私有方法,避免外部误调用,也让代码结构更清晰。
- 图片渲染模式:设置
.alwaysTemplate后,图片会自动使用TabBar的tintColor,和文本颜色保持一致,不用单独给图片做两套颜色的资源。如果你的图片需要保留原色彩,可以删掉这两行代码。
使用方法
- 代码创建TabBarItem:直接用
CustomTabBarItem替代系统的UITabBarItem即可:
let homeTabItem = CustomTabBarItem(title: "首页", image: UIImage(named: "home_icon"), selectedImage: UIImage(named: "home_icon_selected")) let discoverTabItem = CustomTabBarItem(title: "发现", image: UIImage(named: "discover_icon"), selectedImage: UIImage(named: "discover_icon_selected")) // 其他两个TabItem同理
- Storyboard/XIB使用:选中每个TabBarItem,打开「Identity Inspector」,把Class改成
CustomTabBarItem,运行后就会自动应用样式。
之后如果要调整样式,只需要修改customiseTabBarItems方法里的配置,所有TabBarItem都会同步更新,彻底解决重复代码的问题。
内容的提问来源于stack exchange,提问作者marco
相关产品推荐
相关产品推荐

