我正试图让握手姿势起作用。这是一些代码
在我的实施档案
中- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if(event.type == UIEventSubtypeMotionShake)
{
NSLog(@"Shake gesture detected");
}
}
- (BOOL)canBecomeFirstResponder
{
return YES;
}
我读到为了使摇动手势起作用,UIView应该是第一个响应者。这就是我在实现中添加该代码的原因
if(self.view.isFirstResponder)
{
NSLog(@"first");
}
else
{
NSLog(@"no");
}
- (void)viewDidAppear {
[self becomeFirstResponder];
}
当我运行应用程序时,NSLog的输出为NO。我想念的是什么?以及如何让摇动手势工作
答案 0 :(得分:3)
我猜你在你的UIViewController中这样做了吗?这不正确......你必须像这样继承UIView:
ShakeView.h:
//
// ShakeView.h
//
#import <UIKit/UIKit.h>
@interface ShakeView : UIView {
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (BOOL)canBecomeFirstResponder;
@end
ShakeView.m:
//
// ShakeView.m
//
#import "ShakeView.h"
@implementation ShakeView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if ( event.subtype == UIEventSubtypeMotionShake ) {
}
if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] ) {
[super motionEnded:motion withEvent:event];
}
}
- (BOOL)canBecomeFirstResponder
{
return YES;
}
@end
然后使用ShakeView代替你的“普通”UIView并在你的UIViewController中实现它:
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"Shake happend …");
}
- (void)viewDidAppear:(BOOL)animated
{
[self.view becomeFirstResponder];
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[self.view resignFirstResponder];
[super viewWillDisappear:animated];
}
就是这样。希望它有所帮助:)