Swift ScrollViewを一番上までスクロールするサンプル
環境
Swift version 5.2.3 (swift-5.2.3-RELEASE)
構文
ScrollViewReader { reader in
ScrollView {
//処理コード
}
}
ScrollViewを一番上までスクロールするには、ScrollViewReaderを使います。
使用例
struct ContentView: View {
var body: some View {
ScrollViewReader { reader in
VStack {
Button("Scroll") {
withAnimation (.easeInOut){
reader.scrollTo(0)
}
}
ScrollView {
Text("First Item")
.foregroundColor(.blue)
.font(.title)
.padding()
.id(0)
ForEach(1..< 5) { index in
Text("Item \(index)")
.padding()
}
}
}
}
}
}