簡體   English   中英

如何使 `ScrollView` 中的 `VStack` 視圖向上擴展並占據導航標題下的空間,同時將內容保持在同一位置?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM