ios - 使用代码更改 UITabbar 外观

标签 ios iphone swift uitabbarcontroller uitabbar

我正在尝试为我的应用程序应用深色主题,当我调用深色主题时遇到问题,代码在重新启动应用程序之前不起作用。 我在设置 View Controller 中使用 UISwtich 调用黑暗模式。当我打开深色模式时,print 日志将被调用。 这是代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


 NotificationCenter.default.addObserver(self, selector: #selector(darkTheme), name: NSNotification.Name("DARKTHEME"), object: nil)
        darkTheme()

     return true 

}


       @objc func darkTheme()  {

            if appDefaults.darkTheme() == true {

              print("dark mode")

                UITabBar.appearance().barTintColor = UIColor(red:0.16, green:0.16, blue:0.16, alpha:1.00)
                UITabBar.appearance().tintColor = UIColor(red:0.16, green:0.16, blue:0.16, alpha:1.00)

                UITabBar.appearance().isTranslucent = false
                UIApplication.shared.statusBarStyle = .lightContent

            } else {

           print("white mode")

                UITabBar.appearance().barTintColor = UIColor.white
                UITabBar.appearance().tintColor = UIColor.white

                UIApplication.shared.statusBarStyle = .default
                UITabBar.appearance().isTranslucent = true

            }
        }

已编辑:

    //MARK: - Black Theme
    func setDarkTheme(enable:Bool)  {
        UserDefaults.standard.set(enable, forKey: "Dark")
    }

    func darkTheme() -> Bool {
        return UserDefaults.standard.bool(forKey: "Dark")
    }


   @objc func darkMode(_ sender:UISwitch) {



        if sender.isOn {
            appDefaults.setDarkTheme(enable: true)
            print("DARK THEME ON")
        } else {
            appDefaults.setDarkTheme(enable: false)
            print("DARK THEME OFF")
        }

        NotificationCenter.default.post(name: NSNotification.Name("DARKTHEME"), object: nil)

    }

最佳答案

将内容保存到UserDefaults不会立即发生。解决此问题的方法是仅在开始时从 UserDefaults 获取 darkMode 的值。

var shouldChangeUserDefaults = false

var darkMode: Bool {
    didSet {
        if shouldChangeUserDefaults {
            UserDefaults.standard.set(darkMode, forKey: "Dark")
        }
    }
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    [...]

    darkMode = UserDefaults.standard.bool(forKey: "Dark")
    shouldChangeUserDefaults = true

    return true
}

关于ios - 使用代码更改 UITabbar 外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51897810/

相关文章:

javascript - 自动化脚本不起作用?

ios - void _UIPerformResizeOfTextViewForTextContainer 断言失败

iphone - 嵌入的 Youtube 视频在 iPhone 上停止工作

ios - 每次返回单元格时增加一个值

ios - 最佳实践 : exposing NSManagedObject in framework

ios - 从 C 定义 IOS 日志

iphone - 日志调试 Objective-C 代码时使用哪些日志记录解决方案?

ios - 透明的 iOS 导航栏

Swift 2/解析如果 PFUser id 在 Likes 类中相同

ios - Swift:如何存储用户偏好?