簡體   English   中英

如何處理從我的swift應用程序搖動ios設備的支持?

[英]How can I handle support for shaking the ios device from my swift app?

我正在編寫一個ios swift應用程序,我想要包括搖動設備的支持。 至於現在我想在用戶搖動手機時將一個msg打印到控制台。 我找到了這個教程http://www.ioscreator.com/tutorials/detect-shake-gesture-ios8-swift ,它看起來非常簡單,但是有一件事困擾着我。

我希望它可以在應用程序的任何視圖中工作,而不僅僅是單個視圖。 因此,無論用戶當前在應用程序中的哪個位置 - 他都應該能夠調用搖動方法。 我應該在每個面板中實現方法override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { 或者有沒有一種方法可以實現它並在整個應用程序中填充它?

首先,我們可以找出這些“運動”方法的來源,正如文檔所說:

UIResponder類為響應和處理事件的對象定義接口。 它是UIApplication,UIView及其子類的超類。( https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/

運動事件的事件處理方法是:

func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?)
func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?)
func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?)

因此,如您所見,要在應用的每個屏幕上“捕捉”運動事件 - 我們應該在這些屏幕中覆蓋這些方法。 感謝上帝,有了擴展 - 我們可以讓它變得更容易:)

為了使'運動'邏輯更復雜,我們制定一個協議並命名為'MotionDelegate':

protocol MotionDelegate {
func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?)
func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?)
func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?)

}

並制作UIViewController的擴展,符合MotionDelegate協議:

extension UIViewController:MotionDelegate {
override public func becomeFirstResponder() -> Bool {
    return true
}

override public func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake { print("Shaking motionBegan with event\(event)") }
}

override public func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake { print("Shaking motionCancelled with event\(event)") }
}

override public func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake { print("Shaking motionEnded with event\(event)") }
}

}

通過這種方式,運動處理將在您的應用程序的每個UIViewController實例上運行。

要處理某些特定vc上的動作事件,您應該在其擴展名中覆蓋它:

extension MotionViewController {
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake {
        print("MotionViewController Shaking motionEnded with event\(event)")
    }
}

}

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM