Kyronsk8
Kyronsk8

Reputation: 59

How to prevent view from leaving screen in a ScrollView SwiftUI

I want to prevent the 3 bars from leaving the screen. Once they have reached the top of the screen they will remain there until scrolling has been reset. So only the circle and remaining elements will continue to scroll.

If possible it would also make sense for the circle to rest as well but further off screen.

import SwiftUI

struct ContentView: View {
    var body: some View {
        
        ScrollView {
            LazyVStack {
                
                Circle()
                
                HStack {
                    Rectangle()
                        .frame(height: 50)
                        .padding()
                    Rectangle()
                        .frame(height: 50)
                        .padding()
                    Rectangle()
                        .frame(height: 50)
                        .padding()
                    
                }
                
                ForEach(0..<20) { index in
                    VStack {
                        Image(systemName: "globe")
                            .imageScale(.large)
                            .foregroundColor(.accentColor)
                        Text("Hello, world!")
                    }
                    .padding()
                }
                
            }
            .padding()
        }
    }
}

Upvotes: 0

Views: 541

Answers (1)

yawnobleix
yawnobleix

Reputation: 1342

You could turn the rectangles into a section for your LazyVStack list and then set the stack view to pin the section headers using LazyVStack(pinnedViews:[.sectionHeaders]) Please see Apple documentation for more details.

struct ContentView: View {
    var body: some View {
        
        ScrollView {
            LazyVStack(pinnedViews:[.sectionHeaders]) {
                
                Circle()
                
                
                Section(header:
                            HStack {
                    Rectangle()
                        .frame(height: 50)
                        .padding()
                    Rectangle()
                        .frame(height: 50)
                        .padding()
                    Rectangle()
                        .frame(height: 50)
                        .padding()
                    
                }) {
                    ForEach(0..<20) { index in
                        VStack {
                            Image(systemName: "globe")
                                .imageScale(.large)
                                .foregroundColor(.accentColor)
                            Text("Hello, world!")
                        }
                        .padding()
                    }
                }
            }
            .padding()
        }
    }
}

Upvotes: 1

Related Questions