0

我有一个 UIButton,我在外面添加了一个动作 Touch up。我有一个 UIImageView。

我想要以下操作:当用户触摸按钮并在 UIImageView 上释放时,我想要执行 someAction。

如果用户在另一个视图中而不是在 UIImageView 中触摸按钮并释放,则不应执行 someAction。

这是我的代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    NSLog(@"Touch x : %f y : %f", location.x, location.y);
    if(CGRectContainsPoint(redBtn.frame, location)){
        NSLog(@"red button pressed");
    }else if (CGRectContainsPoint(blueBtn.frame, location)){
        NSLog(@"blue button pressed");
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{


    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    if(CGRectContainsPoint(firstImageView.frame, location)){
        if(redFlag){
            [firstImageView setBackgroundColor:[UIColor redColor]];
        }
        else if(blueFlag){
            [firstImageView setBackgroundColor:[UIColor blueColor]];
        }

        NSLog(@"touch ended in first view");
    }else if(CGRectContainsPoint(secondImageView.frame, location)){

        if(redFlag){
            [secondImageView setBackgroundColor:[UIColor redColor]];
        }
        else if(blueFlag){
            [secondImageView setBackgroundColor:[UIColor blueColor]];
        }

        NSLog(@"touch ended in second view");
    }

}
4

1 回答 1

1

用于touchesEnded实现这一点。要检查是否按下按钮,请使用 BOOL,然后在触摸结束时,使用touch.view == imageView然后执行所需的操作。

在按钮单击事件上,创建一个 BOOL 变量 yes 以确保它被按下。现在,在 UIResponser 的 touchesEnded 中写入

UITouch *touch = [touches anyObject]; 
if (touch.view == imageView) 
   {
      // do the required thing here
   }
于 2013-08-27T06:24:58.140 回答