1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftUI特定のアイテムまでスクロールする方法

Posted at

今回はScrollViewReaderを使用して特定のアイテムまでスクロールする実装です。

実装サンプル

SampleScrollViewReader.swift
struct SampleScrollViewReader: View {
    @State private var tee = ["緑茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "烏龍茶", "ほうじ茶", "ジャスミン茶"]
    
    var body: some View {
        ScrollViewReader { proxy in
            ScrollView {
                VStack {
                    Button(action: {
                        proxy.scrollTo(20)
                    }, label: {
                        Text("ジャンプ20")
                    })
                    ForEach (Array(tee.enumerated()), id: \.offset) { offset, item  in
                            VStack(alignment: .center ,spacing: 0) {
                                Text(item + "\(offset)")
                                    .padding()
                                    .font(.system(size: 30))
                                    .frame(maxWidth: .infinity, alignment: .leading)
                                    .id(offset)
                            }.listRowInsets(EdgeInsets())
                    }
                }
            }
        }
    }
}

重要なところは
.id(offset)
で設定した値をproxy.scrollToの引数に入れてあげる事でスクロールします。
現在はOS17は画面一番下に、OS15とOS16は画面一番上になるのでそこは注意が必要です!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?