繁体   English   中英

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

[英]How do I Set Unselected Tab Bar Item Color using Swift in Xcode with an iOS 15+ Device?

我正在尝试使用 Xcode 中的 Swift 自定义 UITabBar,但是我不知道如何使用 window 右侧的菜单设置未选中项目的颜色。我尝试了以下方法:

  1. 我为 TabBarController 定制了一个 class 并实现如下:
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 ...
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。

先感谢您。 我真的很感激我能得到的解决这个问题的任何建议。

我只是面临同样的问题,并为此找到了解决方案。

将此代码放入您的 UITabBarController class

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
 }

这是输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM