将触摸传递给下一个响应者或其他子视图iOS

时间:2012-08-14 15:32:08

标签: iphone objective-c uiview uiimageview touch

我确信这个问题很容易解决,但我对iOS开发相对较新。我正在尝试将触摸事件传递给UIView上绘制顺序较低的子项。例如 -

我创建扩展的UIImageView来创建我的MoveableImage类。这个类基本上是UIImageView,它实现了touchesBegan,touchesEnded和touchesMoved -

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


[self showFrame];

//if multitouch dont move
if([[event allTouches]count] > 1)
{
    return;
}



    UITouch *touch = [[event touchesForView:self] anyObject ];

    // Animate the first touch
    CGPoint colorPoint = [touch locationInView:self];

    CGPoint touchPoint = [touch locationInView:self.superview];


    //if color is alpha of 0 , they are touching the frame and bubble to next responder
    UIColor *color = [self colorOfPoint:colorPoint];
    [color getRed:NULL green:NULL blue:NULL alpha:&touchBeganAlpha];
    NSLog(@"alpha : %f",touchBeganAlpha);

    if(touchBeganAlpha > 0)
    {
          [self animateFirstTouchAtPoint:touchPoint];
    }
    else {
        [super.nextResponder touchesBegan:touches withEvent:event];
    }



}

所以最终的结果基本上是这样的 - 如果他们正在触摸imageView的框架而不是其他图像内部的图像可能会响应。有关示例,请参见此图片。

Passing touch to lower view

到目前为止,我已经尝试了下一个响应者,但这并没有解决问题。任何帮助将不胜感激!

已解决 - 我停止检查touchesBegan和touchesMoved上的alpha。 Ovveriding pointInside允许UIView为我处理。

-(BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *) event
{
  BOOL superResult = [super pointInside:point withEvent:event];
  if(!superResult)
  {
   return superResult;
  }

  if(CGPointEqualToPoint(point, self.previousTouchPoint))
  {
     return self.previousTouchHitTestResponse;
  }else{
     self.previousTouchPoint = point;
  }

  BOOL response = NO;

  //if image is nil then return yes and fall back to super
  if(self.image == nil)
   {
     response = YES;
   }

  response = [self isAlphaVisibleAtPoint:point];
  self.previousTouchHitTestResponse = response;
  return response;





}

1 个答案:

答案 0 :(得分:7)

您可以为UIImageView的子类覆盖- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event方法。 (这是uiview的一种方法,每个子类都可以覆盖)

UIView在hitTest:withEvent:中使用此方法来确定哪个子视图应该接收触摸事件。如果pointInside:withEvent:返回YES,则遍历子视图的层次结构;否则,忽略视图层次结构的分支。

检查OBShapedButton的github上的源代码。它们仅处理按钮的不透明部分的点击事件。