Created
December 31, 2022 10:16
-
-
Save bannzai/e4d524690472c3f53c37c9dcafb9516e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import AVKit | |
struct ContentView: View { | |
@State var soundLabelIsShows = false | |
var body: some View { | |
ZStack(alignment: .center) { | |
Image("kane") | |
.resizable() | |
.scaledToFill() | |
.frame(height: 200) | |
if soundLabelIsShows { | |
Text("ゴ〜ン") | |
.fontWeight(.bold) | |
.font(.system(size: 22)) | |
.transition(.slide) | |
.onAppear { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { | |
soundLabelIsShows = false | |
} | |
} | |
} | |
} | |
.padding() | |
.onShake { | |
sound() | |
soundLabelIsShows = true | |
} | |
} | |
func sound() { | |
var soundIDBell: SystemSoundID = 0 | |
let soundURL = URL(fileURLWithPath: Bundle.main.path(forResource: "kane", ofType:"mp3")!) | |
AudioServicesCreateSystemSoundID(soundURL as NSURL, &soundIDBell) | |
AudioServicesPlaySystemSound(soundIDBell) | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
extension UIDevice { | |
static let deviceDidShakeNotification = Notification.Name(rawValue: "deviceDidShakeNotification") | |
} | |
extension UIWindow { | |
open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { | |
if motion == .motionShake { | |
NotificationCenter.default.post(name: UIDevice.deviceDidShakeNotification, object: nil) | |
} | |
} | |
} | |
struct DeviceShakeViewModifier: ViewModifier { | |
let action: () -> Void | |
func body(content: Content) -> some View { | |
content | |
.onAppear() | |
.onReceive(NotificationCenter.default.publisher(for: UIDevice.deviceDidShakeNotification)) { _ in | |
action() | |
} | |
} | |
} | |
extension View { | |
func onShake(perform action: @escaping () -> Void) -> some View { | |
modifier(DeviceShakeViewModifier(action: action)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment