在运行时更改 UITabBar.appearance().tintColor

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

我想允许用户更改整个应用程序颜色。 但每当我选择一种颜色时,它只会在应用程序重新启动后才会更改。

有没有可以在运行时更改颜色的选项?

我已经设置了一个带有这样的函数的

Button
来创建一个
ColorPicker

@IBAction func colorChange(_ sender: UIButton) {
        // Initializing Color Picker
        let picker = UIColorPickerViewController()

        // Setting the Initial Color of the Picker
        picker.selectedColor = UIColor(named: "MyGreen")!

        // Setting Delegate
        picker.delegate = self

        // Presenting the Color Picker
        self.present(picker, animated: true, completion: nil)
    }

当用户选择颜色时,我会在此函数中进行更改

func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) {
        defaults.set(viewController.selectedColor, forKey: "myColor")
        UITabBar.appearance().tintColor = viewController.selectedColor
    }

要在启动时更改颜色,我已在

AppDelegate

中实现了此功能
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        var myColor = defaults.color(forKey: "myColor")
        if  myColor == nil {
            myColor = UIColor(named: "MyGreen")
        }
        UITabBar.appearance().tintColor = myColor
        
        return true
    }
swift uitabbar color-picker
3个回答
2
投票

有人给了我一篇文章来阅读如何做到这一点。 https://zamzam.io/protocol-orient-themes-for-ios-apps/

我最终这样做了:

 func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) {
        defaults.set(viewController.selectedColor, forKey: "myColor")
        apply(for: UIApplication.shared, color: viewController.selectedColor)
    }

添加此功能

func apply(for application: UIApplication, color: UIColor) {
        UITabBar.appearance().tintColor = color
        application.windows.reload()
    }

以及这些扩展

public extension UIWindow {

    /// Unload all views and add back.
    /// Useful for applying `UIAppearance` changes to existing views.
    func reload() {
        subviews.forEach { view in
            view.removeFromSuperview()
            addSubview(view)
        }
    }
}

public extension Array where Element == UIWindow {
    
    /// Unload all views for each `UIWindow` and add back.
    /// Useful for applying `UIAppearance` changes to existing views.
    func reload() {
        forEach { $0.reload() }
    }
}

我不知道它好不好——但它对我有用。


0
投票

您尝试过使用

UITabBar.appearance().barTintColor
吗?


0
投票

如果您只需要在分配新的

UITabBarAppearance
后重新加载选项卡栏,您可以为视图控制器分配一个新的
UITabBarItem
实例,新的选项卡栏项目将使用更新的
UITabBarAppearance
呈现,没有需要循环浏览窗口中的整个子视图。

let tab = UITabBarItem()
tab.image = UIImage(named: "image")
tab.selectedImage = UIImage(named: "selected_image")
self.tabBarItem = tab
© www.soinside.com 2019 - 2024. All rights reserved.