Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI automatically scroll to bottom in ScrollView (Bottom first)

Tags:

My problem is that i have (in SwiftUI) a ScrollView with an foreach inside. Know when the foreach loads all of my entries i want that the last entry is focused.

I did some google research, but i didn't find any answer.

  ScrollView {     VStack {       ForEach (0..<self.entries.count) { index in         Group {           Text(self.entries[index].getName())         }       }     }   } 
like image 719
Leahpar Avatar asked Oct 14 '19 12:10

Leahpar


People also ask

How do you scroll to the bottom of a ScrollView SwiftUI?

1. Manual scroll to a position with the click of a button. 2. Auto-scroll to the bottom as soon as the view appears.

How do I scroll programmatically in SwiftUI?

If you want to programmatically make SwiftUI's List move to show a specific row, you should embed it inside a ScrollViewReader . This provides a scrollTo() method on its proxy that can move to any row inside the list, just by providing its ID and optionally also an anchor.

What is Lazyvstack?

A view that arranges its children in a line that grows vertically, creating items only as needed.

Is SwiftUI list scrollable?

List view is a container that can present a scrollable list of views in SwiftUI. You can adjust its look, and it supports versatile actions and change its style depending on the platform.


1 Answers

Scrolling to the bottom on change

I don't have enough reputation to post a comment yet, so here you go @Dam and @Evert

To scroll to the bottom whenever the number of entries in your ForEach changes you can also use the same method with a ScrollViewReader, as mentioned in the answer above, by adding the view modifier onChange like so:

struct ContentView: View {     let colors: [Color] = [.red, .blue, .green]     var entries: [Entry] = Array(repeating: Entry(), count: 10)      var body: some View {         ScrollView {             ScrollViewReader { value in                                              ForEach(0..<entries.count) { i in                     Text(self.entries[i].getName())                         .frame(width: 300, height: 200)                         .background(colors[i % colors.count])                         .padding(.all, 20)                 }                 .onChange(of: entries.count) { _ in                     value.scrollTo(entries.count - 1)                 }             }         }     } } 
like image 133
noranraskin Avatar answered Sep 21 '22 06:09

noranraskin