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
}
}
id: 可以是任意 Hashable类型,为了给以后做动画,进行 diff 准备的预留属性。
其他的属性,是用来配置 Cell 的信息
Cell 需要实现 TypedCellType 的方法
update:根据对应的 Item 更新 UI
渲染 UICollectionView
配置 Lego
class ViewController: UIViewController {
var lego: Lego {
Lego {
Section(id: ..., WaterfallLayout()) {
ColorItem(...)
ColorItem(...)
ColorItem(...)
}
Section(WaterfallLayout()) {
for elt in array {
ColorItem(elt)
}
}
}
}
}
LegoKit
使用声明式语法组织 UICollectionView。支持类似 SwiftUI 的
@State
、@Published
和@StateObject
Installation
Swift Package Manager
File > Swift Packages > Add Package Dependency Add https://github.com/octree/LegoKit.git Select “Up to Next Major” with “1.0.0”
How to Use
Cell 的实现
Hashable
类型,为了给以后做动画,进行 diff 准备的预留属性。TypedCellType
的方法Item
更新 UI渲染 UICollectionView
配置 Lego
if
、#if @available
、for in
、switch case
等结构渲染
使用 @State、@StateObject 等,自动更新 CollectionView
@State
或者@StateObject
时就不需要手动调用apply
函数。当数据发生变动时,会自动更新UICollectionView
。License
LegoKit is available under the MIT license. See the LICENSE file for more info.