Home > Mobile >  Scroll to bottom of a list populated with CoreData in SwiftUI
Scroll to bottom of a list populated with CoreData in SwiftUI

Time:11-13

I'm trying to scroll to the bottom of List when a button is tapped. I have tried placing the List in a ScrollViewReader and this seems to work only when the List is populated using an array. When I populate the List using CoreData's FetchedResults the List doesn't scroll for some reason.

var array = Array(0...100)


private var items: FetchedResults<Item>

NavigationView {
        ScrollViewReader { (proxy: ScrollViewProxy) in
            List{
                ForEach(items) {item in
                    
                    Text(item.text!)
                }
            }
            Button("Tap to scroll") {
                
                    proxy.scrollTo(10, anchor: .top)
            }
    }
}

Here if i use items it doesn't scroll but when I replace items with array the list scrolls as expected.

CodePudding user response:

scrollTo() works by receiving an identifier, not an index.

Using array works because 10 is contained in array, but 10 cannot match item.

I would suggest you add an ID String property to your objects (I think you could even use object.uriRepresentation()) tag your views with that identifier, and now you'll be able to use scrollTo.

private var items: FetchedResults<Item>

NavigationView {
        ScrollViewReader { (proxy: ScrollViewProxy) in
            List{
                ForEach(items) {item in
                    Text(item.text!)
                      .id(item.id)
                }
            }
            Button("Tap to scroll") {
                    proxy.scrollTo(items[10].id, anchor: .top)
            }
        }
    }
}
  • Related