はじめに
ScrollViewReaderを使って、特定の行にスクロールする実装を試したので記事に残します。
開発環境
- macOS Big Sur 11.3.1
- Xcode 12.5
- Swift 5.4
サンプルイメージ
実装
ScrollViewReaderでScrollViewProxyのインスタンスを受け取り、インスタンスメソッド"scrollTo(_:anchor:)"で、スクロールしたいの行の識別idとスクロールした時の配置(上部に固定or下部に固定など)を定義する。
※参考
-
https://developer.apple.com/documentation/swiftui/scrollviewreader
-
https://developer.apple.com/documentation/swiftui/scrollviewproxy
-
https://developer.apple.com/documentation/swiftui/scrollviewproxy/scrollto(_:anchor:)
ContentView.swift
import SwiftUI struct ContentView: View { @State private var prefectures = [ "北海道", "青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県", "茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県", "新潟県", "富山県", "石川県", "福井県", "山梨県", "長野県", "岐阜県", "静岡県", "愛知県", "三重県", "滋賀県", "京都府", "大阪府", "兵庫県", "奈良県", "和歌山県", "鳥取県", "島根県", "岡山県", "広島県", "山口県", "徳島県", "香川県", "愛媛県", "高知県", "福岡県", "佐賀県", "長崎県", "熊本県", "大分県", "宮崎県", "鹿児島県", "沖縄県" ] var body: some View { GeometryReader { geometry in ScrollView { ScrollViewReader { proxy in ForEach(Array(zip(prefectures.indices, prefectures)), id: \.0) { index, prefecture in Text(prefecture) .padding() .font(.title3) .onTapGesture { withAnimation(.interactiveSpring(response: 0.1)) { proxy.scrollTo(index, anchor: .top) } } } .frame(width: geometry.size.width, alignment: .leading) } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
おわりに
GeometryReaderやzipなど、本題に関係ないものがサンプルに入っていてわかりにくかったかもしれません・・・機会があれば上記に関する記事も追加しようと思います。