简介:
iOS13苹果推出的暗黑模式,在去年苹果已经声明必须适配暗黑模式否则会下架。
网上有很多好的文章来适配暗黑模式,但是大部分仅仅是以苹果系统、方法来适配的暗黑模式,最大的一个问题是不好做内置的暗黑模式的适配。
所以设计了一个方案,支持APP内置的模式切换。这个方案不说是暗黑模式的适配,更多能应用的是主题切换效果。
思路:
以通知为中心,在切换主题后,发送通知给各个页面,技术通知,设定各个控件颜色。
颜色以白、黑2套,存储在项目中的json文件,设定颜色直接读取json中的16进制,自动根据主题适配。
雏形demo,只提供思路,可以根据项目情况优化。
下面是应用
class ViewController: UIViewController {
lazy var label = { () -> UILabel in
let label = UILabel.init(frame: CGRect(x: 0, y: 200, width: self.view.frame.size.width, height: 40));
label.text = "示例"
return label
}()
lazy var button = { () -> UIButton in
let button = UIButton.init(frame: CGRect(x: 100, y: 300, width: self.view.frame.size.width - 200, height: 40));
button.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)
button.setTitle("切换主题", for: .normal)
return button
}()
lazy var imageView = { () -> UIImageView in
let imageView = UIImageView.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height));
imageView.isUserInteractionEnabled = true
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white;
self.view.addSubview(self.imageView)
self.imageView.addSubview(self.label)
self.imageView.addSubview(self.button)
self.changeColor()
NotificationCenter.default.addObserver(self, selector: #selector(self.changeColor), name: NSNotification.Name(rawValue:"changeColor"), object: nil)
}
@objc func buttonClicked(){
if themeManager.getThemeType() == .dark {
themeManager.changeTheme(type: .light)
}else if themeManager.getThemeType() == .light {
themeManager.changeTheme(type: .dark)
}
}
//改变颜色
@objc func changeColor(){
self.label.backgroundColor = themeManager.getThemeColor(color: "kColor_D00")
self.label.textColor = themeManager.getThemeColor(color: "kColor_foreground")
self.button.backgroundColor = themeManager.getThemeColor(color: "kColor_B01")
self.button.setTitleColor(themeManager.getThemeColor(color: "kColor_D00"), for: .normal)
self.imageView.image = themeManager.getThemeImage(imageName: "image")
}
}