一个解放了 SwiftUI 的 _ScrollView
和 _PagingView
的库。
SolidScroll 允许释放 SwiftUI 中滚动视图的潜力。
与常规的 SwiftUI ScrollView
和 ScrollViewProxy
不同,隐藏的 SwiftUI _ScrollView
和 _ScrollViewProxy
类型允许您实时获得对滚动状态、内容插图 (content insets)、动画内容偏移量等的近乎 UIScrollView 的控制。
SolidScroll 是一组 SwiftUI 隐藏类型的类型别名,以及一些方便的辅助初始化方法。
此外,该库包含 docc 兼容的文档,其中每个类型别名都表示为别名类型的隐藏接口。
SwiftUI 有一个隐藏的 _ContainedScrollViewKey
类型,它实际上是一个未公开遵循的 PreferenceKey
类型。 此首选项报告 _ScrollViewProxy
,其中解锁了 _ScrollView
的所有功能。 为了获得代理,只需在视图的 body
中创建 SolidScrollView
,然后将代理存储在 @State
中,如以下示例所示
import SolidScroll
struct ContentView: View {
var config = ScrollViewConfig()
@State var scrollViewProxy: SolidScrollViewProxy?
var body: some View {
VStack(spacing: 0) {
SolidScrollView(config) {
VStack(spacing: 0) {
Color.red.frame(height: 200)
Color.green.frame(height: 200)
Color.blue.frame(height: 200)
Color.black.frame(height: 200)
}
}
Button("Scroll to 3/4 of the content height via proxy") {
guard let scrollViewProxy = scrollViewProxy else { return }
let contentOffset = CGPoint(x: 0, y: min(scrollViewProxy.contentSize.height * 3.0 / 4, scrollViewProxy.maxContentOffset.y))
scrollViewProxy.setContentOffset(contentOffset, animated: true, completion: { completed in
print("Scrolled via proxy to \(contentOffset)! Completed: \(completed)")
})
}
}
.onPreferenceChange(ContainedScrollViewKey.self) {
scrollViewProxy = $0
}
}
}
对于分页,SwiftUI 有一种不同的隐藏类型,称为 _PagingView
。 它是滚动视图上的一个包装器,支持分页。 滚动的方向和滚动方向的页面大小由 _PagingViewConfig
控制。 所有页面都采用相同的大小。 如果大小为 nil
,则页面在屏幕上占据完整的可用宽度或高度(与滚动方向相对应)。 它对于实现自定义选项卡栏、图像轮播或其他分页行为非常有用。 用例示例如下所示。
import SolidScroll
struct PagingContentView: View {
@State var currentPage: Int = 0
let config: PagingViewConfig
init() {
var config = PagingViewConfig()
config.direction = .horizontal
config.size = 100
config.margin = 0
config.spacing = 0
self.config = config
}
var body: some View {
PagingView(config: config, page: $currentPage, views: Array(0...10).map { page(at: $0) })
}
@ViewBuilder
func page(at index: Int) -> some View {
Text("Page \(index)")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(backgroundColor(at: index))
}
func backgroundColor(at index: Int) -> Color {
let indexMod = (index % 3)
switch indexMod {
case 0: return Color.red
case 1: return Color.green
case 2: return Color.blue
default: return Color.clear
}
}
}
如果想在任何其他使用 SwiftPM 的项目中使用 SolidScroll,请在 Package.swift
中将该包添加为依赖项
dependencies: [
.package(name: "SolidScroll", url: "https://github.com/edudnyk/SolidScroll.git", from: "0.0.1"),
]
接下来,将 SolidScroll 添加为测试目标的依赖项
targets: [
.target(name: "MyApp", dependencies: ["SolidScroll"], path: "Sources"),
]
如果使用 Carthage,可以将以下依赖项添加到 Cartfile
github "edudnyk/SolidScroll" ~> 0.0.1
如果您的项目使用 CocoaPods,请将 pod 添加到 Podfile 中任何适用的目标
target 'MyApp' do
pod 'SolidScroll', '~> 0.0.1'
end