1

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

-(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

        }
4

4 回答 4

5

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

所以你很可能想要

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

您也不会直接创建 UIGestureRecognizer 的实例,而是创建一个具体的子类,在这种情况下为 UISwipeGestureRecognizer。

分配初始化识别器后,将其附加到要识别的视图:

[button addGestureRecognizer:recognizer];

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

下次你最好阅读一些文档。

于 2012-08-12T20:50:03.777 回答
2

除了手势识别器的目标之外,您一切正常。目标是接收给定选择器消息的对象,因此您的initWithTarget:调用应self作为参数接受,除非您在detectSwipe按钮的子类中实现方法。

于 2012-08-12T20:44:36.380 回答
2

您可能想要使用UISwipeGestureRecognizer。UIGestureRecognizer 通常不应使用,除非您将其子类化。您的代码应类似于以下内容。

UISwipeGestureRecognizer *swipe=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(detectSwipe)];
swipe.direction = UISwipeGestureRecognizerDirectionRight;
[button addGestureRecognizer:swipe];
于 2012-08-12T20:51:00.050 回答
1

H2CO3 的答案是完整的。只是不要忘记您在选择器末尾缺少一个冒号“:”!它应该是这样的:@selector(detectSwipe:)

冒号“:”是因为您的方法有一个参数:(UIButton *)sender

于 2012-08-12T21:08:40.473 回答