ios - 按下 UIImageView 时记录的 Touch Up Outside 事件

标签 ios

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

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

如果用户触摸按钮并在 UIImageView 之外的其他 View 中释放,则不应执行 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");
    }

}

最佳答案

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

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

UITouch *touch = [touches anyObject]; 
if (touch.view == imageView) 
   {
      // do the required thing here
   }

关于ios - 按下 UIImageView 时记录的 Touch Up Outside 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18457826/

相关文章:

ios - 使 UITextView 可滚动

ios - 如何快速AirPrint整个屏幕的图片

ios - 从 swift 3.0 中删除语句的 C 样式,successor() 不可用

iphone - iPad Info.plist 未转换为二进制文件

iOS:使 UIButton 始终显示在所有 View 的前面

ios - Xamarin.iOS:使用附加对象创建自定义按钮

iphone - 将NSData转换为字节数组

ios - 将 MKUserTrackingBarButtonItem 移动到导航栏的右侧

ios - 按钮动画无法在 swift 中正常工作

ios - tableheaderview的滚动过程如何实现?