如何在iphone sdk中检查UIView和UIImageView是否被触摸



我有一个UIView和一个可拖动 UIImageViewUIView的背景色为green

当我拖动图像时,UIImageView将触摸UIView。当我把图像拖到UIView上时,UIView的颜色应该变成红色

如何检查UIImageView到达UIView之上

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{   
    if (CGRectIntersectsRect(imageview.frame, view.frame)) {
        view.backgroundColor=[UIColor redcolor];
    }
}

您可以使用touchesBegan方法检查,如以下…

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    [touch locationInView:self.view];
    if([touch.view isKindOfClass:[UIImageView class]])
    {
      ///This is UIImageView
    }
    else if([touch.view isKindOfClass:[UIView class]]) 
    {
      ///This is UIView
    }
}

,当你移动UIImageView时,它会改变UIView的backGroundColor,代码如下…

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *tap = [touches anyObject];
    CGPoint pointToMove = [tap locationInView:self.view];
    if([tap.view isKindOfClass:[UIImageView class]])
    {
        UIImageView *tempImage=(UIImageView *) tap.view;
        if ([yourView pointInside:pointToMove withEvent:event])
        {
            [yourView setBackgroundColor:[UIColor redColor]];
        }
        else{
            [yourView setBackgroundColor:[UIColor clearColor]];//set backcolor which you want when `UIImageView` move outside of yourView 
        }
    }
}

移动UIImage

使用UIPanGestureRecognizer

- (void)onDraggingLetter:(UIPanGestureRecognizer *)panGR {
 CGPoint translation = [panGR translationInView:self.view];
    if (panGR.state == UIGestureRecognizerStateBegan) {
    } else if (panGR.state == UIGestureRecognizerStateChanged) {  
        CGRect _rect = panGR.view.frame;
        _rect.origin.x = dragPoint.x + translation.x;
        _rect.origin.y = dragPoint.y + translation.y;
        panGR.view.frame = _rect;
         if (CGRectIntersectsRect(panGR.view.frame, greenView.frame)) {
               greenView.backgroundColor=[UIColor redColor];
         }
    } else if (panGR.state == UIGestureRecognizerStateEnded) {
    }
}

最新更新