簡介:
iOS13蘋果推出的暗黑模式,在去年蘋果已經(jīng)聲明必須適配暗黑模式否則會(huì)下架。
網(wǎng)上有很多好的文章來適配暗黑模式晌块,但是大部分僅僅是以蘋果系統(tǒng)、方法來適配的暗黑模式帅霜,最大的一個(gè)問題是不好做內(nèi)置的暗黑模式的適配匆背。
所以設(shè)計(jì)了一個(gè)方案,支持APP內(nèi)置的模式切換身冀。這個(gè)方案不說是暗黑模式的適配钝尸,更多能應(yīng)用的是主題切換效果。
思路:
以通知為中心搂根,在切換主題后珍促,發(fā)送通知給各個(gè)頁面,技術(shù)通知剩愧,設(shè)定各個(gè)控件顏色猪叙。
顏色以白、黑2套仁卷,存儲在項(xiàng)目中的json文件穴翩,設(shè)定顏色直接讀取json中的16進(jìn)制,自動(dòng)根據(jù)主題適配锦积。
雛形demo芒帕,只提供思路,可以根據(jù)項(xiàng)目情況優(yōu)化充包。
未命名.gif
下面是應(yīng)用
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")
}
}