2012-08-12 128 views
1

我想添加一个手势识别器到我的按钮,以便我可以运行代码,如果用户刷过按钮框架。如果滑动按钮向上,向右,向左或向下,我还希望此代码有所不同。如何初始化UIGestureRecognizer?

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    button.frame=CGRectMake(0, 0, 100, 100); 
    [self.view addSubview:button]; 
    UIGestureRecognizer *swipe=[[UIGestureRecognizer alloc]initWithTarget:button action:@selector(detectSwipe)]; 
    [button addGestureRecognizer:swipe]; 
} 

那么,我做了initWithTarget:action:的事情是否正确?现在,我这样做,我如何实施detectSwipe方法?

这是我对如何实施detectSwipe

  -(IBAction)detectSwipe:(UIButton *)sender 
     { 
     /* I dont know how to put this in code but i would need something like, 
if (the swipe direction is forward and the swipe is > sender.frame){ 
[self ForwardSwipeMethod]; 
    } else if //same thing for right 
    else if //same thing for left 
    else if //same thing for down 

     } 
+0

detectSwipe:没有得到按钮发件人。它是作为参数传入的手势识别器 - 或者您还会如何知道识别器检测到哪个手势? – 2012-08-12 20:51:22

回答

2

你可能想使用UISwipeGestureRecognizer是。 UIGestureRecognizer通常不应该被使用,除非你继承它。你的代码应该与下面类似。

UISwipeGestureRecognizer *swipe=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(detectSwipe)]; 
swipe.direction = UISwipeGestureRecognizerDirectionRight; 
[button addGestureRecognizer:swipe]; 
2

你有不同的手势识别器的目标的所有正确的想法。目标是接收给定选择器消息的对象,因此您的initWithTarget:调用应接受self作为参数,除非您在按钮的子类中实现detectSwipe方法。

+0

不完全正确。请参阅我答案中的其他要点。 – 2012-08-12 20:52:09

5

不,这是不正确的。手势识别器的目标不是按钮,它是检测手势时调用动作方法的对象(否则它如何知道哪个对象调用该方法?在OO中,方法调用/消息发送需要显式方法名称一个实例或类)。

所以,你很可能想

recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; 

您还没有创建UIGestureRecognizer直接的实例,但是一个如果它的具体子类,UISwipeGestureRecognizer在这种情况下。

后的alloc-initting识别器,将其附加到要被认可的观点:

[button addGestureRecognizer:recognizer]; 

然后在didSwipe:方法,您可以使用手势识别的属性来决定什么大小/距离/其他属性的刷卡是。

You better read some docs next time.

1

H2CO3的答案是完整的。只要不要忘记你在选择器的末尾丢失了冒号“:”!它应该是这样的:@selector(detectSwipe:)

冒号“:”是因为你的方法有一个说法:(UIButton *)sender