检测摇动手势IOS Swift

Fel*_*RsN 20 iphone xcode gesture ios swift

我正在开发一个带有手势系统的应用程序,基本上如果我将iPhone转向左,我的应用程序将执行一项功能,如果我将iPhone转为右,其他功能,与其他人的手势.

我不知道如何使用它,我正在尝试搜索谷歌但不工作,结果只是触摸手势而不是动作手势.

有人有一个教程来帮助我吗?

Spe*_*y99 56

Swift3 ios10:

override func viewDidLoad() {
    super.viewDidLoad()
    self.becomeFirstResponder() // To get shake gesture
}

// We are willing to become first responder to get shake motion
override var canBecomeFirstResponder: Bool {
    get {
        return true
    }
}

// Enable detection of shake motion
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        print("Why are you shaking me?")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 适合Swift 4和iOS 11! (3认同)

Rya*_*nes 16

超级易于实施:

1)让iOS知道哪个视图控制器是响应者链中的第一个:

override func viewDidLoad() {
    super.viewDidLoad()
    self.becomeFirstResponder()
}   
override func canBecomeFirstResponder() -> Bool {
    return true
}
Run Code Online (Sandbox Code Playgroud)

2)以某种方式处理事件:

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if(event.subtype == UIEventSubtype.MotionShake) {
        print("You shook me, now what")
    }
}
Run Code Online (Sandbox Code Playgroud)


bso*_*sod 13

斯威夫特 5
iOS 10+

UIApplicationUIViewControllerUIView、 和UIWindow都是UIResponder默认对象,这意味着它们都可以处理运动事件,例如摇动,无需任何特殊配置。因此,只需覆盖适当的运动方法:

class YourViewController: UIViewController {
    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            print("device did shake")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,您可以覆盖motionBegan(_:with:)motionCancelled(_:with:)。与覆盖某些触摸事件不同,不需要调用 super.


小智 11

这已针对 IOS 12 进行了更新 - 请参阅Apple Docs 您不再需要添加 becomeFirstResponder() 方法。

您只需要在代码中添加motionEnded 函数即可。

override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) 
{
    // code here
}
Run Code Online (Sandbox Code Playgroud)


swi*_*Boy 7

迅捷5

只需将以下方法添加到ViewController并执行代码

override func becomeFirstResponder() -> Bool {
    return true
}

override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){
    if motion == .motionShake {
        print("Shake Gesture Detected")
        //show some alert here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 难道你不应该重写“canBecomeFirstResponder”而不是“becomeFirstResponder”吗?在我将其更改为“canBecomeFirstResponder”之前,这对我不起作用。 (2认同)