如何在iOS 15+设备上使用Xcode中的Swift设置未选中的标签栏项目颜色?

ldioqlga  于 2023-08-02  发布在  Swift
关注(0)|答案(2)|浏览(107)

我试图在Xcode中使用Swift定制UITabBar,但是我不知道如何使用窗口右侧的菜单设置未选中项目的颜色。我尝试了以下方法:
1.我为TabBarController创建了一个自定义类,并按如下方式实现了它:

class CustomTabBarController : UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // set unselectedItemTintColor for UITabBar contained in this Controller...
        self.tabBar.unselectedItemTintColor = UIColor.white
    }
}

字符串
1.当方法1不起作用时,我用以下实现更新了TabBarController的自定义类。

class CustomTabBarController : UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // try setting unselected item tint color using new Appearance API...
        let appearance = UITabBarAppearance()
        
        appearance.backgroundColor = UIColor.white
        appearance.shadowImage = UIImage()
        appearance.shadowColor = UIColor.white

        appearance.stackedLayoutAppearance.normal.iconColor = UIColor.white
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        appearance.stackedLayoutAppearance.normal.badgeBackgroundColor = UIColor.white

        self.tabBar.standardAppearance = appearance
    }
}


这两种实现的方法都不起作用,所以我试图找出哪种方法/实现会起作用。我在运行iOS 15.2的iPhone 11 Pro Max设备模拟器上使用Xcode版本13.2.1和Swift版本5.5.2。
在此先谢谢您!我真的很感激任何建议,我可以得到解决这个问题。

amrnrhlw

amrnrhlw1#

我只是面对同样的问题,并找到解决办法。
将此代码放入UITabBarController类中

if #available(iOS 15, *) {
           let tabBarAppearance = UITabBarAppearance()
            tabBarAppearance.backgroundColor = .white
            tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.red]
            tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.black]
            tabBarAppearance.stackedLayoutAppearance.normal.iconColor = UIColor.black
            tabBarAppearance.stackedLayoutAppearance.selected.iconColor = UIColor.red
            tabBarView.standardAppearance = tabBarAppearance
            tabBarView.scrollEdgeAppearance = tabBarAppearance
 }

字符串

**

*

3htmauhk

3htmauhk2#

只需在运行时属性keypath中添加这一行
for selecetd --> tintColor for not selected --> unselectedItemTintColor

相关问题