XYColor
一个在 CALayer 上适配暗黑模式的简单方法
要求
- iOS 8.0+
- Swift 5.0+
- Xcode 11.0+
安装
使用 CocoaPods 安装
- Swift
pod 'XYColor'
- Objective-C
pod 'XYColorOC'
使用 Carthage 安装
github "RayJiang16/XYColor"
运行 carthage
命令来构建框架,并将适当的框架(根据您的需要为 XYColor.framework
或 XYColorOC.framework
)拖到您的 Xcode 项目中。请确保只添加一个框架,而不是两个。
用法
正如我们大家都知道 UIViewController
和 UIView
有 traitCollection.userInterfaceStyle
属性,但 CALayer
没有。因此,如果 CALayer
想要适配暗黑模式,它需要绑定到一个 UIView
上。这意味着当 UIView.traitCollection.userInterfaceStyle
改变时,CALayer
会改变颜色。
Swift
import XYColor
// View
private var customView: UIView = {
let view = UIView()
...
view.setLayerBorderColor(UIColor.label)
view.setLayerShadowColor(UIColor.label)
view.setLayerBackgroundColor(UIColor.systemBackground)
...
return view
}()
// Layer
private var customLayer: CALayer = {
let layer = CALayer()
...
layer.setBorderColor(UIColor.label, with: customView)
layer.setShadowColor(UIColor.label, with: customView)
layer.setBackgroundColor(UIColor.systemBackground, with: customView)
...
return layer
}()
// Create color
private var color: UIColor = {
return UIColor.create(light: .black, dark: .white)
}()
Objective-C
#import "XYColorOC/XYColorOC.h"
// View
- (UIView *)customView {
...
[_customView xy_setLayerBorderColor:UIColor.labelColor];
[_customView xy_setLayerShadowColor:UIColor.labelColor];
[_customView xy_setLayerBackgroundColor:UIColor.systemBackgroundColor];
...
}
// Layer
- (CALayer *)customLayer {
...
[_customLayer xy_setLayerBorderColor:UIColor.labelColor with:self.customView];
[_customLayer xy_setLayerShadowColor:UIColor.labelColor with:self.customView];
[_customLayer xy_setLayerBackgroundColor:UIColor.systemBackgroundColor with:self.customView];
...
}
// Create color
- (UIColor *)color {
if (!_color) {
_color = [UIColor xy_createWithLightColor:UIColor.blackColor darkColor:UIColor.whiteColor];
}
return _color;
}
许可证
XYColor 使用MIT许可证。更多信息请参阅 LICENSE 文件。