Apple 推荐使用系统颜色让应用程序自动适应明暗模式,例如:
myLabel.textColor = UIColor.secondaryLabel
Here Apple 列出了要使用的各种属性,例如上例中的属性,以及背景、占位符文本等的系统颜色。
但它没有列出 UIButton
元素的属性。
我们应该使用哪个属性或其他方法来使 UIButton 适应主题变化?
截至目前,我正在这样做:
myButton.tintColor = UIColor.link
这应该用于链接,但却是我发现的唯一“可点击”属性。
I'm not looking to use something like
UIColor.systemRed
, rather something likeUIColor.systemBackground
, which adapts automatically to the current theme.
最佳答案
我希望你创建彩色 Assets 不是一个一个。您可以使用此函数为图像着色,作为 UIImageView 的扩展。我也对按钮使用相同的技术。
func setImageAndColor(image: UIImage, color: UIColor) {
let templateImage = image.withRenderingMode(.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
如果您想定义所有您自己的颜色,我建议创建一个名为 Colors 的单例类:
import UIKit
class Colors {
static let shared = Colors()
var statusBarStyle: UIStatusBarStyle = .lightContent
private init(){}
func setLightColors() {
statusBarStyle = .darkContent
yourColor = UIColor( // choose your favorite color
styleColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)//white
labelColor = UIColor(red: 15/255, green: 15/255, blue: 15/255, alpha: 1)
subLabelColor = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 1)
...... 为所有颜色设置值 here .
}
func setDarkColors() {
statusBarStyle = .lightContent
yourColor = // choose your favorite color
............
}
// set initial colors
var yourColor: UIColor =
}
如果有人对整个颜色类(class)感兴趣,请给我发短信或在下面发表评论。
我通过以下方式访问颜色单例: 颜色.shared.yourColor
另外,对于第一个配置,我在第一个 VC 中设置了暗模式编号(0-Auto;1-On;2-Off):
if darkmodeNumber == 0 {
if traitCollection.userInterfaceStyle == .light {
print("Light mode")
Colors.shared.setLightColors()
} else {
print("Dark mode")
Colors.shared.setDarkColors()
}
} else if darkmodeNumber == 1 {
Colors.shared.setDarkColors()
} else if modeNumber == 2 {
Colors.shared.setLightColors()
}
}
状态栏也应该以正确的方式改变。
关于swift - UIButton 的 iOS 13 系统颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56678313/