I was able to achieve the same behavior by changing the anchor of scrollPosition(_:anchor:) to match scrollTo(id:anchor:) before calling:
struct ContentView: View {
@State private var position = ScrollPosition(edge: .top)
@State private var anchor: UnitPoint?
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing: 8) {
ForEach(1..<100) { index in
Text(verbatim: index.formatted())
.frame(maxWidth: .infinity)
.background(.gray)
.id(index)
}
}
}
.scrollPosition($position, anchor: anchor)
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
Spacer()
Button("50 (T)") {
anchor = .top
withAnimation {
position.scrollTo(id: 50, anchor: .top)
}
}
Button("50 (B)") {
anchor = .bottom
withAnimation {
position.scrollTo(id: 50, anchor: .bottom)
}
}
Spacer()
}
}
}
}
}