NerdzStyle 库允许您轻松地创建 CSS 样式的风格并将其应用于视图元素。
您需要创建一个样式才能在之后使用它。您可以通过两种方式来实现。
let borderedViewStyle = UIView.style {
$0.layer.borderWidth = 1
$0.layer.borderColor = UIColor.white.cgColor
$0.layer.cornerRadius = 16
}
let borderedViewStyle = Style<UIButton> {
$0.layer.borderWidth = 1
$0.layer.borderColor = UIColor.white.cgColor
$0.layer.cornerRadius = 16
}
您还可以从另一个样式继承以创建自定义层级结构
let plainButtonStyle = UIButton.style(parent: borderedViewStyle) {
$0.setTitleColor(.green, for: .normal)
$0.layer.borderColor = UIColor.green.cgColor
$0.titleLabel?.font = UIFont.preferredFont(forTextStyle: .largeTitle)
}
let plainButtonStyle = Style<UIButton>(parent: borderedViewStyle) {
$0.setTitleColor(.green, for: .normal)
$0.layer.borderColor = UIColor.green.cgColor
$0.titleLabel?.font = UIFont.preferredFont(forTextStyle: .largeTitle)
}
要将 Style
应用到某个视图实例,您可以使用以下两种可能的方式之一
myButton.apply(plainButtonStyle)
plainButtonStyle.apply(to: myButton)
您也可以一次应用多个样式。样式优先级将从左到右递增
myButton.apply(buttonStyle1, buttonStyle2, buttonStyle3)
您还可以将相同的样式应用于多个视图
plainButtonStyle.apply(to: button1, button2, button3)
由于使用了泛型,您将被迫使用与您应用样式的视图类型相同的泛型参数。如果您想应用具有另一个泛型参数的样式 - 您可以使用 Style
类中的 wrapped
函数
myButton.apply(borderedViewStyle.wrapped())
您可以使用 CocoaPods 依赖管理器来安装 NerdzStyle
。在您的 Podfile
中指定
pod 'NerdzStyle', '~> 1.0'
要将 NerdzStyle 添加到基于 Swift Package Manager 的项目中,请添加
.package(url: "https://github.com/nerdzlab/NerdzStyle")
此代码在 MIT 许可证下分发。有关更多信息,请参阅 LICENSE
文件。