I\'m developing a app with a gesture system, basically if I turn the iPhone to left my app will do a function, if I turn the iPhone to Right, other function, with others ges
Speedy99's swift answer is in the Objective C version
- (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?");
}
}
Swift 5
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.becomeFirstResponder()
}
override var canBecomeFirstResponder: Bool {
get {
return true
}
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("shake")
}
}
}
This has been updated for IOS 12 - see Apple Docs You no longer need to add becomeFirstResponder() method.
You just need to add motionEnded function to your code.
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?)
{
// code here
}
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: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Why are you shaking me?")
}
}
Super easy to implement:
1) Let iOS know which view controller is the first in the responder chain:
override func viewDidLoad() {
super.viewDidLoad()
self.becomeFirstResponder()
}
override func canBecomeFirstResponder() -> Bool {
return true
}
2) Handle the event in some fashion:
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if(event.subtype == UIEventSubtype.MotionShake) {
print("You shook me, now what")
}
}
swift Docs:- https://developer.apple.com/documentation/uikit/uiresponder .
To detect motion events swift has provided 3 methods:-
func motionBegan() -> Tells the receiver that motion has begun
func motionEnded() -> Tells the receiver that a motion event has ended
For example if you want to update image after shake gesture
class ViewController: UIViewController {
override func motionEnded(_ motion: UIEvent.EventSubtype, with event:
UIEvent?)
{
updateImage()
}
UpdateImage(){
// Implementation
}
}