1
1

More than 1 year has passed since last update.

【SwiftUI】matchedGeometryEffectを使って拡大機能を作成する

Posted at

はじめに

@NamespacematchedGeometryEffectを使って滑らかなアニメーションを実装することができるので拡大機能を実装してみました

サンプルアプリ

Simulator Screen Recording - iPhone 14 Pro - 2023-07-30 at 22.58.30.gif

実装

import SwiftUI

struct ContentView: View {
    @State private var selectedEmoji: String?

    @Namespace private var namespace
    
    private let emojis = ["☺️", "😄", "😆", "😀", "😤", "😠", "🥱", "😮‍💨", "😫", "😭", "😂", "😢"]
    
    private let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 3)
    
    var body: some View {
        if let emoji = selectedEmoji {
            Text(emoji)
                .font(.system(size: 100))
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color(uiColor: .cyan))
                .onTapGesture {
                    withAnimation {
                        selectedEmoji = nil
                    }
                }
                .matchedGeometryEffect(id: emoji, in: namespace)
        } else {
            ScrollView {
                LazyVGrid(columns: columns, spacing: 10) {
                    ForEach(emojis, id: \.self) { emoji in
                        Text(emoji)
                            .font(.system(size: 50))
                            .frame(maxWidth: .infinity)
                            .frame(height: 80)
                            .background(Color(uiColor: .cyan), in: RoundedRectangle(cornerRadius: 10))
                            .onTapGesture {
                                withAnimation {
                                    selectedEmoji = emoji
                                }
                            }
                            .matchedGeometryEffect(id: emoji, in: namespace)
                    }
                }
                .padding(16)
            }
        }
    }
}

おわり

めっちゃいい感じになりました
これを応用したらかっこいいアプリが作れそうです!

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