Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI reverse ScrollView from bottom to top

I want to make a ScrollView that will give me the possibility to scroll from bottom to top. Basically I have a gradient background (bottom - black, top - white). When I set the ScrollView I can scroll down from white to black. I want the app to start at the bottom of ScrollView, to give me the possibility to scroll upwards. (From Black to White)

Thank you!

Current code:

struct ContentView: View {
var body: some View {


    ScrollView(.vertical/*, showsIndicators: false*/){
        VStack(spacing: 0) {
            ForEach ((0..<4).reversed(), id: \.self) {
                Image("background\($0)").resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: UIScreen.main.bounds.width ,height:1000)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.red)
    }
    .edgesIgnoringSafeArea(.all)

}   

}

like image 560
Vanfen Avatar asked Feb 19 '26 22:02

Vanfen


2 Answers

I wanted the scrollview to appear bottom to top instead of top to bottom. This had my answer: https://www.thirdrocktechkno.com/blog/implementing-reversed-scrolling-behaviour-in-swiftui/

TLDR: .rotationEffect(Angle(degrees: 180)).scaleEffect(x: -1.0, y: 1.0, anchor: .center) on the scrollview AND on the items in the scrollview

My full code:


ScrollView(.vertical, showsIndicators: true, content: {
                LazyVStack(alignment: .center, spacing: nil, pinnedViews: [], content: {
                    ForEach(1...5, id: \.self) { count in
                        ScrollView(.horizontal, showsIndicators: false, content: {
                            LazyHStack(alignment: .center, spacing: nil, pinnedViews: [], content: {
                                ForEach(1...10, id: \.self) { count in
                                    Text("Placeholder \(count)").rotationEffect(Angle(degrees: 180)).scaleEffect(x: -1.0, y: 1.0, anchor: .center)
                                }
                            })
                        })
                    }
                })
            }).rotationEffect(Angle(degrees: 180)).scaleEffect(x: -1.0, y: 1.0, anchor: .center)

like image 171
jonmecer Avatar answered Feb 22 '26 12:02

jonmecer


Apple has an API for this if you're using iOS 17+

ScrollView() {
    // content
}
.defaultScrollAnchor(.bottom)
like image 28
teradyl Avatar answered Feb 22 '26 13:02

teradyl