简体   繁体   中英

How to Implement shake gestures in an Apple Watch application?

The WatchKit reference seems to make no mention about it. Have I missed something? Or is it really not possible to implement a shake gesture in an Apple Watch application?

The following is a typical example of a shake gesture implementation on iOS:

// MARK: Gestures
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
    if(event.subtype == UIEventSubtype.MotionShake) {
        // do something
    }
}

No, it is not possible to do anything having to do with UIEvent s in WatchKit right now, with the current solution's "remoted UI" approach where you mostly just get to tell the watch how to use the pre-arranged UI from the storyboard and react to actions like tapping a button or a table row. There will be support for a lot more code running on the watch later this year, according to Apple.

Update: Native apps are now possible for watchOS 2. This functionality may be present.

This is now possible in Watch OS2 with CMMotionManager a part of CoreMotion.

You can have this workaround.

let motionManager = CMMotionManager()
if (motionManager.accelerometerAvailable) {
   let handler:CMAccelerometerHandler = {(data: CMAccelerometerData?, error: NSError?) -> Void in

       if (data!.acceleration.z > 0) {
          // User did shake
       }
   }
   motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: handler)
}

How Roger say, an workaround is use the CoreMotion.

You can use coreMotion to get movement. I build this simple wrapper on my Github.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM