LoginSignup
1
1

[SwiftUI]Buttonのタップと長押しで遷移先を変えたい

Posted at

はじめに

Buttonのタップと長押しの両方を共存させて処理を変えたいと思って試しに実装してみました。
開発時用の設定画面に遷移させたい、みたいなシーンで使えるかも?

コード全文

サンプルコード
import SwiftUI

struct ContentView: View {
    @State var isLongPress = false
    @State var isTap = false
    
    var body: some View {
        NavigationStack {
            Button {
            } label: {
                Text("押せ!!")
            }
            .navigationDestination(isPresented: $isLongPress) {
                SecondView()
                    .navigationTitle("SecondView")
            }
            .navigationDestination(isPresented: $isTap) {
                ThirdView()
                    .navigationTitle("ThirdView")
            }
            .simultaneousGesture(
                LongPressGesture(minimumDuration: 0.4)
                    .onEnded { _ in
                        print("long press gesture")
                        isLongPress.toggle()
                    }
            )
            .simultaneousGesture(
                TapGesture()
                    .onEnded { _ in
                        print("tap gesture")
                        isTap.toggle()
                    }
            )
            .navigationBarTitleDisplayMode(.inline)
            .navigationTitle("Home")
        }
    }
}

struct SecondView: View {
    var body: some View {
        Text("SecondView")
    }
}

struct ThirdView: View {
    var body: some View {
        Text("ThirdView")
    }
}

スクリーンショット

画面収録 2023-12-20 1.20.15.gif

おわりに

Buttonでタップと長押しのジェスチャーを共存させる方法って他にもっといい方法あるかもしれないです。

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