How to let expanding content of SwiftUI ScrollView stick to top?

I have a ScrollView with ForEach content. By clicking the 'show all' button, a filter on the Array in the ForEach is removed and the list expands. However, I would like the ScrollView to stick to the top. I use a GeometryReader to expand the content to the correct width.

      ScrollView([.horizontal, .vertical], showsIndicators: false) {
        VStack {
          HStack(alignment: .top) {
            
            ///The left row of symptoms
            symptomRow()
            symptomValues()
            
          }
          
          Spacer()
        }
        .overlay(
          GeometryReader { geo in
            Color.clear.preference(key: WidthPreferenceKey.self, value: geo.size.width)
          })
        .padding(.bottom)
      }

Scrollview content expanding, but the scrollview automatically scrolls down.

Upvotes: 1

Views: 1172

Answers (1)

trianglejerry00
trianglejerry00

Reputation: 614

The question says that you want the ScrollView to be fixed at the top. Are you saying that you want to secure the Row with the "Show All" button on the top?

import SwiftUI

struct ContentView: View {
    
    @State var symptomsNum: Int = 100
    @State var LabtestsNum: Int = 100
    
    var body: some View {
        
        ScrollView {
            LazyVStack(spacing:0, pinnedViews: .sectionHeaders) {
                Section(header: HeaderView(title: "symptoms", forNum: $symptomsNum)) {
                    ForEach (1 ..< symptomsNum, id: \.self) { num in
                        Text("\(num)")
                    }
                }
                Section(header: HeaderView(title: "Labtests", forNum: $LabtestsNum)) {
                    ForEach (1 ..< LabtestsNum, id: \.self) { num in
                        Text("\(num)")
                    }
                }
            }
        }
        .padding()
        .background(.white)
    }
    
    struct HeaderView: View {
        
        let title: String
        @Binding var forNum: Int
        
        var body: some View {
            HStack {
                Text(title)
                Spacer()
                Button {
                    forNum = forNum == 100 ? 200 : 100
                } label: {
                    Text(forNum == 100 ? "Show all" : "Show less")
                }
            }
            .background(.white)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Upvotes: 4

Related Questions