潘手势识别按钮问题

时间:2015-02-04 23:21:31

标签: objective-c xcode

我设置了一个平移手势识别器来识别我对某些按钮的触摸,并且遇到了以下问题。我正在尝试为每个按钮添加一个动作。我通过告诉每个不同的按钮在我触摸它们时突出显示来测试它。到目前为止,当我将手指按在屏幕上时,只滑动按钮1和按钮2显示(如代码中所示)。

但出于某种原因,当我单独按下它们时,我仍然可以看到其他按钮以相同的方式突出显示。任何想法如何解决这个问题,以便他们只回应。如果button.tag == 3等。然后回复?这是代码。 (这是项目中的所有代码和界面构建器中的几个按钮。)

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

// Add Gesture to track the finger
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
[self.view addGestureRecognizer:pan];
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateChanged) {
    CGPoint point = [gesture locationInView:self.view];

    for (UIButton *button in [self.view subviews]) {
        if ([button isKindOfClass:[UIButton class]]) {

            if (button.tag == 1) {
                button.highlighted = CGRectContainsPoint(button.frame, point);

            } else if (button.tag == 2) {
                button.highlighted = CGRectContainsPoint(button.frame, point);
            } //
        }
    }
}
else if (gesture.state == UIGestureRecognizerStateEnded)
{
    for (UIButton *button in [self.view subviews]) {
        if ([button isKindOfClass:[UIButton class]]) {
            button.highlighted = NO;
        }
    }
}

}

编辑:

[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanned:)];
- (void)handlePanned:(UIPanGestureRecognizer*)thePanner{

if (thePanner.state == UIGestureRecognizerStateChanged ){
   //disable button 
}else if (thePanner.state == UIGestureRecognizerStateEnded) {
    //enable button
}else if ( thePanner.state == UIGestureRecognizerStateFailed ){
 //enable button
}
}

1 个答案:

答案 0 :(得分:0)

您没有检查您所触摸的位置是否位于按钮所在位置。

我看到的最快解决方案是:

为每个按钮创建属性,我们称之为button1button2button3

创建您的panGestureRecognizer

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];

    [self.view addGestureRecognizer:pan];
}

处理平底锅的方法:

-(void)handlePanGesture:(UIPanGestureRecognizer *)gesture
{
    //create a CGpoint so you know where you are touching  
    CGPoint touchPoint = [gesture locationInView:self.view];

    //just to show you where you are touching...
    NSLog(@"%@", NSStringFromCGPoint(touchPoint));

    //check your button frame's individually to see if you are touching inside it
    if (CGRectContainsPoint(self.button1.frame, touchPoint))
    {
        NSLog(@"you're panning button1");
    }
    else if(CGRectContainsPoint(self.button2.frame, touchPoint))
    {
        NSLog(@"you're panning button2");
    }
    else if (CGRectContainsPoint(self.button3.frame, touchPoint))
    {
        NSLog(@"you're panning button3");
    }

那应该是它。