如何以编程方式更改标签栏项目使用的默认图标?
Posted
技术标签:
【中文标题】如何以编程方式更改标签栏项目使用的默认图标?【英文标题】:How to programmatically change the default icon used by a tab bar item? 【发布时间】:2020-03-02 04:25:13 【问题描述】:我有一个TabBar
项目,它是一个名为“购物车”的购物车大纲。这是XCode
提供的默认图标。使用按钮的选项卡,我想将此图标更改为XCode
提供的另一个默认图标,称为“cart.fill”
shoppingCartIcon.image = UIImage(named: "cart.fill")
我已经尝试了上述方法,但是这不起作用。有没有我忽略的简单解决方案?
【问题讨论】:
看到这个寻求帮助:how to programmatically change the tabbarItem's image 【参考方案1】:您可以在这个类中进行与标签栏相关的所有自定义。只需将此类 TabbarViewController 分配给情节提要中的 UITabbarController 并相应地自定义所有图像和标题。
class TabbarViewController: UITabBarController
override func viewDidLoad()
super.viewDidLoad()
let arrayOfImageNameForUnselectedState = ["home_unselected","info_unselected","puzzle","video","more"]
let arrayOfImageNameForSelectedState = ["home_selected","info_selected"]
let titlesArray = ["Home","About Us"]
// Do any additional setup after loading the view.
if let count = self.tabBar.items?.count
for i in 0...(count-1)
let imageNameForSelectedState = arrayOfImageNameForSelectedState[i]
let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]
self.tabBar.items?[i].title = titlesArray[i]
self.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState )?.withRenderingMode(.alwaysOriginal)
self.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState )?.withRenderingMode(.alwaysOriginal)
let selectedColor = UIColor(red: 233.0/255.0, green: 41.0/255.0, blue: 47.0/255.0, alpha: 1.0)
let unselectedColor = UIColor(red: 127.0/255.0, green: 140.0/255.0, blue: 141.0/255.0, alpha: 1.0)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: unselectedColor], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: selectedColor], for: .selected)
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
【讨论】:
以上是关于如何以编程方式更改标签栏项目使用的默认图标?的主要内容,如果未能解决你的问题,请参考以下文章
在 viewDidLoad() 中以编程方式更改标签栏项目标题