2015-11-03 90 views
6

我正在開發一個帶有手勢系統的應用程序,基本上如果我將iPhone左轉,我的應用程序將執行一項功能,如果我將iPhone轉換爲右,其他功能以及其他手勢。檢測搖動手勢iOS Swift

我不知道如何處理,我試圖搜索谷歌,但不工作,結果是隻觸摸手勢,而不是運動的手勢。

有人有一個教程來幫助我?

+0

我建議您正在尋找運動事件:https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/motion_event_basics/ motion_event_basics.html – dalipsia

回答

7

超級容易實現:

1)設的iOS知道哪個視圖控制器在響應者鏈中的第:

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.becomeFirstResponder() 
} 
override func canBecomeFirstResponder() -> Bool { 
    return true 
} 

2)手柄以某種方式的情況下:

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

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?") 
    } 
} 
+2

適合Swift 4和iOS 11! –

0

Speedy99的迅速回答是目標C版本

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self becomeFirstResponder]; 
} 

- (BOOL)canBecomeFirstResponder{ 
    return true; 
} 

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{ 
    if(event.subtype == UIEventSubtypeMotionShake){ 
     NSLog(@"Why are you shaking me?"); 
    } 
}