0
1

More than 1 year has passed since last update.

【SwiftUI】端末を振ったことを検知する

Posted at

はじめに

端末を振ったことを検知するとランダムに色が変更されるアプリを作成します

サンプルアプリ

端末を振ると色が変化します
Simulator Screen Recording - iPhone 14 Pro - 2023-07-23 at 22.40.54.gif

実装

extension NSNotification.Name {
    public static let deviceDidShakeNotification = NSNotification.Name("DeviceDidShakeNotification")
}

extension UIWindow {
    open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        super.motionEnded(motion, with: event)
        NotificationCenter.default.post(name: .deviceDidShakeNotification, object: event)
    }
}

使い方

import SwiftUI

struct ContentView: View {
    @State private var color: Color = .orange
    
    var body: some View {
        Text(color.description)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .ignoresSafeArea()
            .background(color.gradient)
+           .onReceive(NotificationCenter.default.publisher(for: .deviceDidShakeNotification)) { _ in
+               color = .init(red: Double.random(in: 0...1), green: Double.random(in: 0...1), blue: Double.random(in: 0...1))
+           }
    }
}

おわり

シェイクを使った個人開発アプリをリリースしたいです

参考記事

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