📦 基于 KeyPath dynamicMemberLookup 的 Swift 语法糖。
let label: UILabel = UILabel().ductTape
.numberOfLines(0)
.textColor(.red)
.text("Hello, World!!")
以上等同于以下定义。
let label: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textColor = .red
label.text = "Hello, World!!"
return label
}()
NSObject 已经兼容 DuctTape,所以你可以像下面这样访问 .ductTape
属性。
let builder: Builder<UIView> = UIView().ductTape
如果你访问 .ductTape
,它会返回一个 Builder
,它通过 KeyPath dynamicMemberLookup 提供属性的 setter。
let view: UIView = UIView().ductTape
.backgroundColor(.red)
.translatesAutoresizingMaskIntoConstraints(false)
如果你想访问正在构建的对象的方法,可以使用 func reinforce(_ handler: (Base) -> Void) Builder<Base>
来访问方法。
let collectionView: UICollectionView = UICollectionView().ductTape
.backgroundColor(.red)
.reinforce { collectionView in
collectionView.register(UITableViewCell.self, forCellWithReuseIdentifier: "Cell")
}
Builder
拥有 func reinforce<T1, ...>(_ t1: T1, ..., handler: (Base) -> Void) Builder<Base>
方法。 进一步,如果将对象作为参数传递,则可以使用 func reinforce
来访问外部对象。
lazy var collectionView: UICollectionView = UICollectionView().ductTape
.translatesAutoresizingMaskIntoConstraints(false)
.reinforce(view) { collectionView, view in
view.addSubview(collectionView)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: collectionView.topAnchor),
view.leadingAnchor.constraint(equalTo: collectionView.leadingAnchor),
view.trailingAnchor.constraint(equalTo: collectionView.trailingAnchor),
view.bottomAnchor.constraint(equalTo: collectionView.bottomAnchor)
])
}
有两种方式使用 DuctTape。
class Dog: DuctTapeCompatible {
var name: String
}
let dog: Dog = Dog().ductTape
.name("Copernicus")
class Dog {
var name: String
}
let dog: Dog = Builder(Dog())
.name("Copernicus")
class ViewController: UIViewController {
let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
.ductTape
.minimumLineSpacing(10)
.minimumInteritemSpacing(10)
.itemSize(CGSize(width: 100, height: 100))
.scrollDirection(.vertical)
lazy var collectionView: UICollectionView = UICollectionView(frame: .zero,
collectionViewLayout: flowLayout)
.ductTape
.dataSource(self)
.delegate(self)
.translatesAutoresizingMaskIntoConstraints(false)
.reinforce {
$0.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: collectionView.topAnchor),
view.leadingAnchor.constraint(equalTo: collectionView.leadingAnchor),
view.trailingAnchor.constraint(equalTo: collectionView.trailingAnchor),
view.bottomAnchor.constraint(equalTo: collectionView.bottomAnchor)
])
}
}
DuctTape 可以通过 CocoaPods 获取。要安装它,只需将以下行添加到你的 Podfile
中
pod "DuctTape"
如果你正在使用 Carthage,只需将 DuctTape 添加到你的 Cartfile
中
github "marty-suzuki/DuctTape"
只需将以下行添加到你的 Package.swift
中
.package(url: "https://github.com/marty-suzuki/DuctTape.git", from: "version")
DuctTape 使用 MIT 许可证发布。