LoginSignup
2
3

【SwiftUI】Viewをジェスチャーで回転させる(iOS17)

Posted at

はじめに

iOS17からRotateGesture()という機能が追加されました。
これを使用してジェスチャーでViewを回転させることができます。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2024-01-02 at 21.29.58.gif

実装

公式ドキュメントにあるコードです。

import SwiftUI

struct ContentView: View {
    @State private var angle = Angle(degrees: 0.0)

    var rotation: some Gesture {
        RotateGesture()
            .onChanged { value in
                angle = value.rotation
            }
    }

    var body: some View {
        Rectangle()
            .frame(width: 200, height: 200, alignment: .center)
            .rotationEffect(angle)
            .gesture(rotation)
    }
}

解説

現在の角度を格納している変数です。

@State private var angle = Angle(degrees: 0.0)

現在の角度をrotationEffectでViewに反映させています。

Rectangle()
    .frame(width: 200, height: 200, alignment: .center)
    .rotationEffect(angle)
    .gesture(rotation)

上記コードのgesturerotationを指定しています。
rotationは以下のようになっています。
RotateGesture()が変化するとvalueで値が流れてきます。
value内のrotationを取得して、現在の角度を更新しています。

var rotation: some Gesture {
    RotateGesture()
        .onChanged { value in
            angle = value.rotation
        }
}

おわり

iOS17から使えるようになるのでちゃんと使われるようになるのはまだ先だと思いますが、SwiftUIが便利になってきてて嬉しいですね

2
3
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
2
3