はじめに
端末を振ったことを検知するとランダムに色が変更されるアプリを作成します
サンプルアプリ
実装
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))
+ }
}
}
おわり
シェイクを使った個人開発アプリをリリースしたいです
参考記事