我正在尝试使用GeometryReader
将maxHeight分配给Scrollview
中的列表。
出于这个问题的目的,我创建了以下项目:GeometryReaderTesting。
它使用设置ContentView
:
-文字。
-清单。
-文字。
我使用@ViewBuilder
将列表和最后一个文本提取到了自己的视图中,我想将列表的maxHeight设置为用户屏幕高度的.5。
问题在于该应用程序不会生成以下错误,并且GeometryReader似乎无法计算正确的高度:
这是我的ContentView代码,如果有人知道我在做什么错...
struct ContentView: View {
let arrayWithStuff = [ "one","two","three","four","five","six","seven","eight","nine","ten", "eleven", "twelve"]
var heightOfView: CGFloat = 0.0 // To be set by GeometryReader
var body: some View {
let myString = "Top of Test App"
return ZStack {
GeometryReader { g in
heightOfView = g.size.height
NavigationView {
print("height of view : \(heightOfView)")
ScrollView {
VStack {
Text(myString)
.padding()
Divider()
self.ViewBody()
} // END of Vstack
.navigationBarTitle("Test App", displayMode: .inline)
} // END of Scrollview
}//End of NavigationView
} // End of Geometry reader
} // End of Zstack
} // End of body
@ViewBuilder func ViewBody() -> some View {
VStack {
List {
ForEach (self.arrayWithStuff, id: \.self) { item in
Text(item) }
} // END of List
.frame(maxHeight: heightOfView*0.5)
Divider()
Text("Bottom of TEST APP")
}
.padding()
}
}
再次,我们将不胜感激。
答案 0 :(得分:2)
这里是可能解决方案的演示。经过Xcode 11.4的测试。
struct ContentView: View {
let arrayWithStuff = [ "one","two","three","four","five","six","seven","eight","nine","ten", "eleven", "twelve"]
var body: some View {
let myString = "Top of Test App"
return ZStack {
GeometryReader { g in
NavigationView {
ScrollView {
VStack {
Text(myString)
.padding()
Divider()
self.ViewBody(height: g.size.height)
} // END of Vstack
.navigationBarTitle("Test App", displayMode: .inline)
} // END of Scrollview
}//End of NavigationView
} // End of Geometry reader
} // End of Zstack
} // End of body
func ViewBody(height: CGFloat) -> some View {
print("height of view : \(height)")
return VStack {
List {
ForEach (self.arrayWithStuff, id: \.self) { item in
Text(item) }
} // END of List
.frame(height: height*0.5)
Divider()
Text("Bottom of TEST APP")
}
.padding()
}
}