如何解决可滚动内容在 SwiftUI 中无法按预期工作
我正在尝试使用自定义视图创建滚动视图,但是当我添加滚动视图时,它无法按预期工作,滚动视图也无法正常工作。
struct ContentView: View {
var body: some View {
ScrollView(.vertical) {
vstack {
ForEach (0..<2) { _ in
ListItem()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
// But the below code is working fine.
struct ContentView: View {
var body: some View {
vstack {
ForEach (0..<2) { _ in
ListItem()
}
}
}
}
// List Item
struct ListItem: View {
var body: some View {
vstack {
HStack {
Image("steve")
.resizable()
.clipShape(Circle())
.aspectRatio(contentMode: .fit)
.frame(maxWidth:44,maxHeight: 44)
vstack {
Text("Steve Jobs")
.font(.headline)
.frame(maxWidth: .infinity,alignment: .leading)
Text("1 hour ago")
.font(.footnote)
.frame(maxWidth: .infinity,alignment: .leading)
}
Spacer()
}
ZStack(alignment:.top) {
GeometryReader { geometry in
vstack {
ZStack {
Image("poster_1")
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(8)
.shadow(color: Color.black.opacity(0.12),radius: 4,x: 1,y: 1)
.frame(width: geometry.size.width - 64,height: geometry.size.height * 0.35)
.padding([.horizontal],32)
.clipped()
ZStack {
Rectangle()
.fill(Color.black.opacity(0.75))
.frame(maxWidth:84,maxHeight: 84)
.cornerRadius(12)
Image(systemName: "play.fill")
.font(.system(size: 44,weight: .bold))
.foregroundColor(.white)
}
}
vstack {
Text("Game of Thrones")
.accentColor(Color.gray.opacity(0.25))
.font(Font.subheadline.weight(.bold))
.padding([.horizontal],32)
.padding([.bottom],2)
.frame(maxWidth: .infinity,alignment: .leading)
vstack {
Text("Game of Thrones is an American fantasy drama television series created by David Benioff and D. B. Weiss for HBO. ")
.accentColor(Color.gray.opacity(0.25))
.font(.footnote)
.frame(maxWidth: .infinity,alignment: .leading)
.padding([.horizontal],32)
Text("Show more...")
.accentColor(Color.gray.opacity(0.01))
.font(Font.footnote.weight(.bold))
.frame(maxWidth: .infinity,alignment: .trailing)
.padding([.trailing],32).onTapGesture {
print("okay")
}
}
}
}
}
}
}
}
}
ListItem 包含多个视图,用于创建发行商信息和电影信息,如下图所示。
Scrollview 正在滚动,但图像未作为第一张图像显示在视图中。
解决方法
它是您在 ListItem
中的几何阅读器。因为 GeometryReader 和 Scrollview 都没有自己的大小。由于既没有要渲染的大小,它们就崩溃了。这就是你在你的观点中看到的。见this answer。解决方案是将 GeometryReader
放入 ContentView
之外的 Scrollview
并将您称为 GeometryProxy
的 geometry
发送到 ListItem
中,如下所示:
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
ScrollView(.vertical) {
VStack {
ForEach (0..<2) { _ in
ListItem(geometry: geometry)
}
}
} // Scrollview
} // GeometryReader
}
}
struct ListItem: View {
let geometry: GeometryProxy
var body: some View {
...
}
这似乎在预览中修复了它,尽管您可能需要更改使用 .frame()
的 geometry
中的乘数来调整您想要的大小。最后,为了加强@jnpdx,当您制作一个最小的可重复示例时,请将您的资产中的图像切换为形状或按原样工作的东西。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。