Skip to content

Instantly share code, notes, and snippets.

@ole
Created November 17, 2022 10:40
Show Gist options
  • Save ole/ca325b65013bc6cdf4b8e168eabd0572 to your computer and use it in GitHub Desktop.
Save ole/ca325b65013bc6cdf4b8e168eabd0572 to your computer and use it in GitHub Desktop.
SwiftUI: control List scroll position on element insert
import SwiftUI
struct Item: Identifiable {
var id: UUID = .init()
var value: Int
}
let sampleItems: [Item] = (1...99).map { Item.init(value: $0) }
struct ContentView: View {
@State private var items: [Item] = sampleItems
var body: some View {
NavigationStack {
ScrollViewReader { proxy in
List(items) { item in
Text("\(item.value)")
.id(item.id)
}
.toolbar {
ToolbarItem {
Button("Add") {
withAnimation {
let firstID = items.first?.id
let newItem = Item(value: Int.random(in: 500...1000))
items.insert(newItem, at: 0)
if let firstID {
proxy.scrollTo(firstID, anchor: .top)
}
}
}
}
}
}
.navigationTitle("List")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@ole
Copy link
Author

ole commented Nov 17, 2022

When a new item is added at the top, keep the list's scroll position constant. This kinda works, but only with .navigationBarTitleDisplayMode(.inline) and the animation is ugly (tested in iOS 16.1).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment