簡體   English   中英

在UIView的邊界上使用碰撞

[英]Using collision on bounds of UIView

我有一個在UIView周圍移動的ImageView,是否可以檢測到ImageView及其視圖自身的碰撞? 例如,ImageView擊中了我希望它執行操作的視圖的側面。 -(void)restart {}如果可能,您可以檢測到它與哪一側發生了碰撞?

您可以創建一個自定義UIImageVIew並實現touchBegan和touchMoved方法(不要忘記在init方法中添加[self setUserInteractionEnabled:YES] )。 然后設置要與之交互的矩形:

customImageView.interactRect = myView.frame;

在您的customImageView中,您可以添加以下內容:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    lastPosition = [touch locationInView: self.superview];
}

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

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint position = [touch locationInView:self.superview];
    CGRect currentFrame = self.frame;
    currentFrame.origin = CGPointMake(currentFrame.origin.x + position.x - lastPosition.x, currentFrame.origin.y + position.y - lastPosition.y);

    if (CGRectIntersectsRect(currentFrame, interactRect) && !CGRectIntersectsRect(self.frame, interactRect))
    {
        NSLog(@"I'm in for the first time");
        if(self.frame.origin.x + self.frame.size.width <= interactRect.origin.x &&    currentFrame.origin.x + currentFrame.size.width > interactRect.origin.x)
        {
            NSLog(@"Coming from the left");
        }
        if(self.frame.origin.x >= interactRect.origin.x + interactRect.size.width && currentFrame.origin.x < interactRect.origin.x + interactRect.size.width)
        {
            NSLog(@"Coming from the right");
        }
    }
    self.frame = currentFrame;
    lastPosition = position;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM