iOS 使用Tabman库时如何将TMBarItem的标题替换为自定义图片


你需要替换的图标资源如下:
实现方法
TMBarItem 原生支持直接设置图片作为展示内容,无需通过文字标题实现,按以下步骤修改即可:
- 先将整理好的6个图标资源导入到项目的
Assets.xcassets中,按索引顺序分别命名方便调用,例如tab_all、tab_gs25、tab_cu、tab_ministop、tab_7eleven、tab_emart。 - 替换你现有
barItem生成方法,直接给TMBarItem传入image参数,不需要设置title即可只展示图片:
func barItem(for bar: TMBar, at index: Int) -> TMBarItemable { switch index { case 0: return TMBarItem(title: nil, image: UIImage(named: "tab_all")) case 1: return TMBarItem(title: nil, image: UIImage(named: "tab_gs25")) case 2: return TMBarItem(title: nil, image: UIImage(named: "tab_cu")) case 3: return TMBarItem(title: nil, image: UIImage(named: "tab_ministop")) case 4: return TMBarItem(title: nil, image: UIImage(named: "tab_7eleven")) case 5: return TMBarItem(title: nil, image: UIImage(named: "tab_emart")) default: return TMBarItem(title: nil, image: nil) } }
如果需要调整图标大小、间距、选中态效果,可以额外添加TMBar的按钮自定义配置:
// 配置全局bar样式 bar.layout.interItemSpacing = .fixed(24) // 调整标签之间的间距 bar.layout.contentInset = UIEdgeInsets(top: 10, left: 16, bottom: 10, right: 16) // 自定义每个按钮的样式 bar.buttons.customize { button in button.imageView.contentMode = .scaleAspectFit button.imageViewSize = CGSize(width: 32, height: 32) // 统一设置图标大小 button.titleLabel.isHidden = true // 完全隐藏文字区域 // 如果需要设置选中/未选中的 tint 颜色,给图标添加渲染模式即可 // button.imageView.tintColor = .systemGray // button.selectedImageView.tintColor = .systemRed }
如果你的图标本身是彩色不需要全局tint变色,不需要设置渲染模式,直接使用默认的图片渲染效果即可。
内容的提问来源于stack exchange,提问作者장서영
相关产品推荐
相关产品推荐

