Gor*_*yan 17 scrollview ios swift swift5 swiftui
我正在使用 swiftUI 进行编码,并且我有一个垂直的scrollView(参见屏幕截图),在其中scrollView我有另一个水平的scrollView,在其下面我有一个VStack我希望高度将屏幕的其余部分填充到垂直的底部scrollView,但我似乎无法让它发挥作用。
在某些情况下,垂直方向的内容scrollView可能大于实际剩余空间,这就是为什么我需要滚动视图,但在其他一些情况下,内容小于剩余空间
这是我的代码:
VStack {
HeaderView
ScrollView(.vertical, showsIndicators: false) {
FriendsHorizontalScrollView()
VStack {
// I want this view to take all the remaining height left in the scrollView
FullHeightView()
}
.frame(width: UIScreen.main.bounds.width)
}
}
Run Code Online (Sandbox Code Playgroud)
我最终得到的是这样的:
我想要拥有什么:
我尝试了几种解决方案,例如使用 GeometryReader 或安装.frame(maxHeight: .infinity),VStack但似乎都无法正常工作。
Mur*_*tam 43
这可以通过使用来实现GeometryReader。这个想法是设置minHeight你的根视图:
import SwiftUI
struct ContentView: View {
var body: some View {
GeometryReader { proxy in
ScrollView {
VStack(spacing: 0) {
Text("View 1")
.frame(height: 100)
.frame(maxWidth: .infinity)
.background(Color.green)
Text("View 2")
.frame(height: 100)
.frame(maxWidth: .infinity)
.background(Color.gray)
VStack {
Text("VStack")
Text("View 3")
.frame(height: 100)
.frame(maxWidth: .infinity)
.background(Color.blue)
.padding()
}
.frame(maxHeight: .infinity)
.background(Color.yellow)
}
.frame(minHeight: proxy.size.height)
}
}
.edgesIgnoringSafeArea(.all)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Run Code Online (Sandbox Code Playgroud)
这是基于视图首选项的可能方法的演示(ViewHeightKey取自我的此解决方案。使用 Xcode 12 / iOS 14 进行测试。
struct DemoLayoutInScrollView: View {
@State private var height1: CGFloat = .zero
@State private var height2: CGFloat = .zero
var body: some View {
VStack(spacing: 0) {
HeaderView()
GeometryReader { gp in
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 0) {
FriendsHorizontalScrollView()
.background(GeometryReader {
Color.clear
.preference(key: ViewHeightKey.self, value: $0.frame(in: .local).size.height)
})
.onPreferenceChange(ViewHeightKey.self) { self.height1 = $0 }
VStack(spacing: 0) {
// I want this view to take all the remaining height left in the scrollView
FullHeightView()
.background(GeometryReader {
Color.clear
.preference(key: ViewHeightKey.self, value: $0.frame(in: .local).size.height)
})
}.frame(height: max(gp.size.height - self.height1, self.height2))
.background(Color.yellow)
}
}
.onPreferenceChange(ViewHeightKey.self) { self.height2 = $0 }
}
}.frame(maxWidth: .infinity)
}
}
Run Code Online (Sandbox Code Playgroud)
复制的辅助视图(用于测试)
struct FriendsHorizontalScrollView: View {
var body: some View {
Text("Horizontal Scroller")
.frame(maxWidth: .infinity)
.frame(height: 100)
.background(Color.green)
}
}
struct FullHeightView: View {
var body: some View {
ZStack {
Color.red
Text("Dynamic Content")
}
.frame(maxWidth: .infinity)
.frame(height: 300)
}
}
struct HeaderView: View {
var body: some View {
Rectangle().foregroundColor(.blue)
.frame(height: 60)
.overlay(Text("Header"))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13762 次 |
| 最近记录: |