LoginSignup
1
0

[コピペで動く]SwiftUIで写真アプリのような左右スワイプで、画像切り替えをするサンプルコード!

Last updated at Posted at 2023-05-19

宣伝

アプリ作っているので入れてみてください!!
よろしくお願いいたします!!

本題

このコードは、SwiftUIを使用して画像ビューアーを作成するものです。画像配列を受け取り、スワイプ操作に応じて画像を切り替える機能を提供します。

これをベースにして、必要に応じてカスタマイズや機能追加を行い、自分のプロジェクトに適した画像ビューアーを実装してみてください。

ImageViewerに画像の配列を渡せばそれらの写真を表示できます。

struct ContentView: View {
    let images: [UIImage] = [
        UIImage(systemName: "arrow.up.left.and.arrow.down.right")!,   // UIImageの配列を定義し、システムアイコンのUIImageを格納します
        UIImage(systemName: "arrow.left.and.right.circle.fill")!,
        UIImage(systemName: "arrowtriangle.up.fill")!,
    ]

    var body: some View {
        ImageViewer(images: images)   // ImageViewerに定義したViewを生成し、渡す画像配列を指定して表示します
    }
}

struct ImageViewer: View {
    let images: [UIImage]   // 画像配列を受け取るプロパティを定義します
    @State private var currentIndex = 0   // 現在の画像のインデックスを管理するStateを定義します
    @GestureState private var translation: CGFloat = 0   // スワイプの移動量を管理するStateを定義します

    var body: some View {
        ZStack {
            ForEach(images.indices, id: \.self) { index in   // 画像配列の要素数分繰り返し、画像を表示します
                Image(uiImage: images[index])   // UIImageを表示するImageビューを生成します
                    .resizable()   // サイズ変更可能にします
                    .aspectRatio(contentMode: .fit)   // アスペクト比を保ちながらフィットさせます
                    .frame(width: UIScreen.main.bounds.width)   // 幅を画面の幅に合わせます
                    .offset(x: (CGFloat(index) - CGFloat(currentIndex)) * UIScreen.main.bounds.width + translation)   // スワイプに応じて画像を移動させます
                    .animation(.interactiveSpring())   // インタラクティブなスプリングアニメーションを適用します
            }
            .gesture(
                DragGesture()
                    .updating($translation) { value, state, _ in   // スワイプの移動量を更新します
                        state = value.translation.width
                    }
                    .onEnded { value in   // スワイプ終了時に実行される処理です
                        let offset = value.translation.width
                        let threshold: CGFloat = UIScreen.main.bounds.width * 0.2   // 画像切り替えの閾値を設定します
                        if offset < -threshold && currentIndex < images.count - 1 {   // 左方向のスワイプで次の画像に移動します
                            currentIndex += 1
                        } else if offset > threshold && currentIndex > 0 {   // 右方向のスワイプで前の画像に移動します
                            currentIndex -= 1
                        }
                    }
            )
        }
    }
}


作ったアプリ。

では。

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