How to make a ScrollView start at the bottom
How to make a ScrollView start at the bottom 관련
Updated for Xcode 15
New in iOS 17
SwiftUI's ScrollView
starts scrolling from the top by default, but if you want to create a UI like Apple's Messages app you can ask the scroll view to start at the bottom by using the scrollPosition()
modifier with an initial anchor of .bottom
.
For example, this shows 50 text views in a scroll view, but asks the scroll view to start its position from the bottom rather than the top:
ScrollView {
ForEach(0..<50) { i in
Text("Item \(i)")
.frame(maxWidth: .infinity)
.padding()
.background(.blue)
.clipShape(.rect(cornerRadius: 25))
}
}
.scrollPosition(initialAnchor: .bottom)
If your UI alters somehow without the user scrolling – for example if the keyboard appears, or you adjust the size of the scroll view – then the scroll position will remain anchored to the bottom. However, if the user adjusts the scroll position manually, it will scroll freely as normal.
Tips
The initialAnchor
parameter is any UnitPoint
, so you can use .trailing
to start a horizontal scroll view from the right edge, or any exact value you need for your UI.