[英]Using custom UIView class with Auto Layout returns incorrect bounds
[英]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.