Skip to content

Commit

Permalink
Adds shake gesture view modifier (#64)
Browse files Browse the repository at this point in the history
Adds shake gesture view modifier implementing override on motionEnded on UIWindow using NotificationCenter to broadcast motion detection
  • Loading branch information
LukasLiebl authored Aug 25, 2023
1 parent 7746162 commit b62dd45
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Sources/UIExtensions/Extensions/UIWindow+MotionEnded.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright © 2023 Lautsprecher Teufel GmbH. All rights reserved.

import UIKit

extension NSNotification.Name {
public static let didShakeDevice = NSNotification.Name("DidShakeDeviceNotification")
}

extension UIWindow {
override open func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
super.motionEnded(motion, with: event)

switch event?.subtype {
case .motionShake:
NotificationCenter.default.post(name: .didShakeDevice, object: event)
default: break
}
}
}
19 changes: 19 additions & 0 deletions Sources/UIExtensions/ViewModifiers/ShakeGestureViewModifier.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright © 2023 Lautsprecher Teufel GmbH. All rights reserved.

import SwiftUI

struct ShakeGestureViewModifier: ViewModifier {
let action: () -> Void

func body(content: Content) -> some View {
content.onReceive(NotificationCenter.default.publisher(for: .didShakeDevice)) { _ in
action()
}
}
}

extension View {
public func onShakeGesture(perform action: @escaping () -> Void) -> some View {
self.modifier(ShakeGestureViewModifier(action: action))
}
}

0 comments on commit b62dd45

Please sign in to comment.