WatchLayout
需求
iOS 13+
安装
CocoaPods
WatchLayout 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中
UIKit | SwiftUI |
---|---|
pod 'WatchLayout' |
pod 'WatchLayout-SwiftUI' |
Swift 包管理器
dependencies: [
.package(url: "https://github.com/HocTran/WatchLayout.git", .upToNextMajor(from: "1.1.0"))
]
使用方法
UIKit
let layout = WatchLayout()
支持配置
设置集合视图单元格的项目大小。
layout.itemSize = 200
设置单元格项目间距。减号表示项目可以重叠。默认值 0。
layout.spacing = -40
设置中心项目旁边项目的缩放比例。默认值 0.4
layout.nextItemScale = 0.4
根据距离中心的位置设置项目的最小缩放比例。默认值 0.2
layout.minScale = 0.2
为 UICollectionView 分配自定义布局
collectionView.collectionViewLayout = layout
滚动到索引路径的项目
self.collectionView.setContentOffset(layout.centeredOffsetForItem(indexPath: IndexPath(item: 0, section: 0)), animated: true)
获取当前中心索引
layout.centeredIndexPath
SwiftUI
SwiftUI 版本构建在 WatchLayout
的 UIViewRepresentable
之上。
声明布局属性(参见上述 UIKit 使用中每个参数的详细说明)。
@State var layout = WatchLayoutAttributes(
itemSize: 120,
spacing: 16,
minScale: 0.2,
nextItemScale: 0.6
)
创建并将布局属性分配给视图。
-
data:用于计算集合的 RandomAccessCollection(或 Binding)。
-
centeredIndex:(可选) 用于识别集合中心索引的绑定。
WatchLayoutView(
layoutAttributes: layout,
data: data,
centeredIndex: $centeredIndex,
cellContent: ({ dataElement in
// Build up your cell content here
Text(dataElement.description)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(dataElement.color)
.clipShape(Circle())
})
如果 data 元素是 hashable,中心绑定可以是数据元素。
WatchLayoutView(
layoutAttributes: layout,
data: data,
centeredItem: $centeredItem,
cellContent: ({ dataElement in
// Build up your cell content here
Text(dataElement.description)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(dataElement.color)
.clipShape(Circle())
})
屏幕截图
定位 | 滚动 |
---|---|
![]() |
![]() |
示例 01 | 示例 02 |
---|---|
![]() |
![]() |
示例
要运行示例项目,克隆仓库,打开 WatchLayout.xcworkspace
。
UIKit
-
选择方案
WatchLayout
,然后按 Cmd+B 编译框架。 -
选择方案
Example-iOS
,然后运行示例。
SwiftUI
-
选择方案
WatchLayout
,然后按 Cmd+B 编译框架。 -
选择方案
WatchLayout-SwiftUI
,然后按 Cmd+B 编译框架。 -
选择方案
Example-iOS
,然后运行示例。
作者
HocTran,[email protected]
许可证
WatchLayout 适用于 MIT 许可证。更多信息请参阅 LICENSE 文件。