Created
November 17, 2022 10:40
-
-
Save ole/ca325b65013bc6cdf4b8e168eabd0572 to your computer and use it in GitHub Desktop.
SwiftUI: control List scroll position on element insert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).