使用声明式语法组织 UICollectionView。支持类似 SwiftUI 的 @State
、@Published
和 @StateObject
File > Swift Packages > Add Package Dependency 添加 https://github.com/octree/LegoKit.git 选择 "Up to Next Major" 并选择 "1.0.0"
public struct ColorItem: TypedItemType {
public typealias CellType = ColorCell
public var id: UUID
public var color: UIColor
public var height: CGFloat
}
public class ColorCell: UICollectionViewCell, TypedCellType {
public typealias Item = ColorItem
public func update(with item: ColorItem) {
backgroundColor = item.color
}
}
Hashable
类型,为了给以后做动画,进行 diff 准备的预留属性。TypedCellType
的方法Item
更新 UIclass ViewController: UIViewController {
var lego: Lego {
Lego {
Section(id: ..., WaterfallLayout()) {
ColorItem(...)
ColorItem(...)
ColorItem(...)
}
Section(WaterfallLayout()) {
for elt in array {
ColorItem(elt)
}
}
}
}
}
if
、#if @available
、for in
、switch case
等结构class ViewController: UIViewController {
lazy var legoRenderer: LegoRenderer = .init(lego: lego)
override func viewDidLoad() {
legoRenderer.render(in: view) {
$0.backgroundColor = UIColor(white: 0.95, alpha: 1)
}
}
private func reload() {
legoRenderer.apply(lego)
}
}
class ViewModel: LegoObservableObject {
@LegoPublished var items: [ColorItem] = []
func addRandomColor() {
items.append(.random)
}
}
class ViewController: UIViewController, LegoContainer {
@StateObject var viewModel = ViewModel()
@State var flag: Bool = false
lazy var legoRenderer: LegoRenderer = .init(lego: lego)
var lego: Lego {
Lego {
Section(id: 0, layout: WaterfallLayout()) {
if flag {
// ... some items.
}
viewModel.items
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
legoRenderer.render(in: view) {
$0.backgroundColor = UIColor(white: 0.95, alpha: 1)
}
}
}
@State
或者 @StateObject
时就不需要手动调用 apply
函数。当数据发生变动时,会自动更新 UICollectionView
。LegoKit 基于 MIT 许可证发布。 详情请查看 LICENSE 文件。