如何以编程方式更改选项卡栏项目使用的默认图标?

问题描述 投票:0回答:1

我有一个TabBar项目,它是一个购物车轮廓,称为“购物车”。这是XCode提供的默认图标。使用按钮的选项卡,我想将此图标更改为XCode提供的另一个默认图标,称为“ cart.fill”

shoppingCartIcon.image = UIImage(named: "cart.fill")

我已经尝试了上面的方法,但是这没有用。有一个我忽略的简单解决方案吗?

ios swift xcode uitabbar uitabbaritem
1个回答
0
投票

您可以在此类中与标签栏相关的所有自定义项。只需将此类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.
    }


}
© www.soinside.com 2019 - 2024. All rights reserved.