DEBuilder
最漂亮的 Builder
DEBuilder 默认提供 UIKit 的 视图和控件 Builder。
通过继承,也可以方便地创建自定义对象。
用法
基础
let view = UIView.Builder()
.withGestureRecognizers(tapGesture)
.withCornerRadius(8, maskedCorners: [.layerMaxXMaxYCorner, .layerMaxXMinYCorner])
.disableTranlatesAutoresizing()
.build()
或者您也可以直接访问。
let view = ViewBuilder()
.withGestureRecognizers(tapGesture)
.withCornerRadius(8, maskedCorners: [.layerMaxXMaxYCorner, .layerMaxXMinYCorner])
.disableTranlatesAutoresizing()
.build()
如果您想使用在自定义视图中继承的对象的 Builder,您可以使用以下代码。
class CustomButton: UIButton {
typealias Builder = ButtonBuilder<CustomButton>
}
// Usage 1
let customButton = CustomButton.Builder()
.withTitle([("CustomButtonTitle", .normal)])
.disableTranlatesAutoresizing()
.build()
// Usage 2
let customButton = ButtonBuilder<CustomButton>
.withTitle([("CustomButtonTitle", .normal)])
.disableTranlatesAutoresizing()
.build()
使用
继承自 NSObject 的对象可以使用 keypath 默认设置属性。
在您使用 Builder 创建对象之后,您可以使用 with
方法设置 Builder 没有提供的属性。
let label = UILabel.Builder()
.withText("Custom Label")
.disableTranlatesAutoresizing()
.build()
.with(\.font, setTo: font)
.with(\.textAlignment, setTo: textAlignment)
当自定义类没有继承自 NSObject 时,您可以按照以下方式实现 With
协议。
class CustomClass: With {
var customProperty: String
}
let custom = CustomClass()
.with(\.customProperty, setTo: "Custom")
自定义 Builder
如果DEBuilder没有您想要的构建器,您可以自行实现。
class CustomLabel: UILabel {
var customProperty: String?
}
class CustomLabelBuilder: LabelBuilder<CustomLabel> {
private var customProperty: String?
override func build() -> CustomLabel {
return super.build()
.with(\.customProperty, setTo: customProperty)
}
func withCustomProperty(_ customProperty: String?) -> CustomLabelBuilder {
self.custom
}
}
如果您没有要继承的构建器,您可以采用BuilderType
来实现自定义构建器。
class CustomObject {
var customProperty: String?
}
class CustomObjectBuilder: BuilderType {
private var customProperty: String?
func build() -> CustomObject {
return CustomObject()
.with(\.customProperty, setTo: customProperty)
}
func withCustomProperty(_ customProperty: String?) -> CustomObjectBuilder {
self.custom
}
}
安装
您只能使用Cocoapods安装此库。
pod 'DEBuilder'
许可证
DEBuilder使用MIT许可证提供。更多信息请参阅LICENSE文件。