我正在try 实现一个类似于Instagram Reels用户界面的抓拍滚动视图.内容在SwiftUI中,滚动视图是一个包含在UIViewRepresentable
中的UIScrollView
.我在UIScrollView
上启用了分页功能,以获得滚动时对齐项目功能.
滚动视图的内容只是我设置为屏幕全宽和全高的一些文本:
struct FeedView: View {
var body: some View {
VStack(spacing: 0) {
Text("")
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
.background(.red)
Text("")
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
.background(.green)
Text("")
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
.background(.blue)
}
}
}
可表示的滚动视图如下:
struct ScrollSnapView: UIViewRepresentable {
func makeUIView(context: Context) -> UIScrollView {
let view = UIScrollView()
view.isPagingEnabled = true
view.showsVerticalScrollIndicator = false
view.showsHorizontalScrollIndicator = false
view.contentInsetAdjustmentBehavior = .never
let child = UIHostingController(rootView: FeedView())
child.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 3)
view.contentSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 3)
view.addSubview(child.view)
return view
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
}
}
然后我用主 struct 中的ignoreSafeArea
实例化一个ScrollSnapView
:
@main
struct App: App {
var body: some Scene {
WindowGroup {
ScrollSnapView()
.ignoresSafeArea()
}
}
}
以下是滚动的录音:
如你所见,当我滚动到第二页时,在顶部可以看到一个小红色.当我滚动到第三页时,可以看到一个小绿色.我怎么才能把UIScrollView
页精确到每页的边界呢?
我试着在makeUIView
页中删除这一行:
view.contentInsetAdjustmentBehavior = .never
它包括分页时的安全区域边界(我不想要,我想完全隐藏安全区域),但至少它完全滚动到每一页的顶部边界.
我试了this个答案,但不起作用.