TheMultiplexer
TheMultiplexer

Reputation: 325

SwiftUI - ScrollViewReader scroll to top including padding (anchor plus constant)

I have a ScrollViewReader and the scrollTo method works.

proxy.scrollTo(target, anchor: .top)

The item which is scrolled to is completely aligned with the .top-Anchor.

enter image description here

Now I want to include the padding of 7px. Is there a SwiftUI equivalent to the NSLayoutAnchor below or any other method to make the green overlay always align with the List-Element.

NSLayoutAnchor(equalTo:self.view.topAnchor constant:7)

Upvotes: 6

Views: 1809

Answers (1)

Thien Vu
Thien Vu

Reputation: 1

SwiftUI ScrollView prevent developers from scrolling to a custom position, but we can find another way to simulate the padding.

Examples:

ScrollViewReader { proxy in
                ScrollView(.vertical) {
                    VStack() {
                        ForEach(programs) { program in
                            buildProgramView(program: program)
                                .offset(y: 7) // --> This line make a top padding
                                .tag(id)
                        }
                    }
                }
                .onChange(of: programTarget) { target in
                    withAnimation {
                        proxy.scrollTo(target, anchor: .top)
                    }
                }
            }

Good luck !

Upvotes: 0

Related Questions