![](/img/trans.png)
[英]Content inside VStack shrinks when embedded inside a ScrollView in SwiftUI
[英]How to make `VStack` view inside `ScrollView` expand up and take the space under navigation title while keeping the content in the same spot?
這是我目前擁有的示例:
struct ContentView: View {
var body: some View {
NavigationView {
ScrollView {
VStack() {
Text("Foo")
}
.frame(maxWidth: .infinity, idealHeight: 200)
.background(Color(uiColor: .systemBackground))
}
.background(Color(uiColor: .secondarySystemBackground))
.navigationTitle("Title")
}
}
}
我想要實現的是白色背景一直到屏幕頂部,同時保留填充,以便VStack
的實際內容顯示在標題下方而不是標題下方,當滾動發生時VStack
的內容跟隨標題從大到內聯。
好吧,我找到了一種方法來做到這一點。 它很笨拙,很可能無法在所有屏幕尺寸或改變設備方向時正常工作,但我認為它適用於大多數縱向模式的 iPhone 機型。
我的想法是在ScrollView
中放置一個ZStack
,並將我的VStack
與所需顏色的Rectangle
一起放置在那里,然后將Rectangle
向上偏移以占據導航欄下方的空間,並在滾動 spring 效果發生時保持顏色相同。
這是代碼:
struct ContentView: View {
var body: some View {
NavigationView {
ScrollView {
ZStack(alignment: .top) {
Rectangle()
.foregroundColor(Color(uiColor: .systemBackground))
.frame(height: UIScreen.main.bounds.height * 0.5)
.offset(y: -UIScreen.main.bounds.height * 0.5)
.padding(.bottom, -UIScreen.main.bounds.height * 0.5)
VStack() {
Text("Foo")
}
.frame(maxWidth: .infinity)
.frame(height: 200)
.background(Color(uiColor: .systemBackground))
}
}
.background(Color(uiColor: .secondarySystemBackground))
.navigationTitle("Title")
}
}
}
注意:不要忘記將alignment: .top
設置為ZStack
!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.