LoginSignup
0
1

More than 1 year has passed since last update.

SwiftUIのScrollView メモ

Posted at

ScrollView

swift
// 縦スクロール
ScrollView(.vertical) {
            
}

// 横スクロール
ScrollView(.horizontal) {
            
}

// これでも横スクロール
ScrollView() {
    HStack {
                    
    }
}

// スクロール禁止 インジケータ非表示
ScrollView([], showsIndicators: false) {
            
}

ScrollViewReader

スクロール制御したい部分を囲めば上手く適用ができます。
また、ScrollViewProxyインスタンスが取得できます。
各要素(ForEach)に一意のIDをタグつける→ScrollToで指定ちまでジャンプすることができる。

swift
@State private var newIndex: Int = 0


ScrollViewReader { scrollproxy in // ScrollViewProxyインスタンスを取得
    ScrollView(.horizontal) {
        ForEach(1..<100) {
            Text("\($0) 行目").font(.title)
                .id($0)         // スクロール先を指定する為の一意のIDを指定
        }
    🌟example
        Button(action: {
            // 15番目に移動
            scrollProxy.scrollTo(15, anchor: .top)
        }) {
            Text("Tap Me!")
        }
    }
}

注意

ScrollViewにDragGestureを付与する際は、
スクロールビュー自体のスクロールジェスチャーを無効化にしなければドラッグジェスチャーは効かないためドラッグジェスチャーに以下を適用する

swift
DragGesture(minimumDistance: 0.0)

これでスクロールのジェスチャーよりドラッグジェスチャーが優先になる
(そもそもスクロールビューのスクロールを禁止していれば適用しなくていい)

swift
ScrollViewReader { scrollproxy in // ScrollViewProxyインスタンスを取得
    ScrollView([], showsIndicators: false) {
        HStack {
            ForEach(1..<100) {
                Text("\($0) 行目").font(.title)
                    .id($0)         // スクロール先を指定する為の一意のIDを指定
                }
            }
        }
        .gesture(
            DragGesture(minimumDistance: 0.0) // ドラッグ距離
                .onEnded() {
                    // ドラック終了時アクション
                }
        )
}

他気になることあれば随時更新する

0
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
0
1