经过多次谷歌搜索后仍然没有找到任何解决方案,我提出一个问题。
我的问题是:- 我想在特定区域拖动我的 View ,除此之外,我不希望我的 View 被拖动,但它应该在指定的 View 中可拖动。 如果拖动超出,我能够停止拖动,但是当我触摸它在允许的区域中拖动时,它不会拖动。
My code:-
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch *touch=[touches anyObject];
CGPoint pt = [[touches anyObject] locationInView:touch.view];
startLocation = pt;
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
// Move relative to the original touch point
UITouch *touch=[touches anyObject];
CGPoint pt = [[touches anyObject] locationInView:touch.view];
CGPoint pt2 = [[touches anyObject] locationInView:self.view];
if ([touch.view isKindOfClass:[MyView class]]) {
CGRect frame = [touch.view frame];
CGRect prevFrame=[touch.view frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
CGRect boundsA = [touch.view convertRect:touch.view.bounds toView:nil];
CGRect boundsB = [self.canvasVw convertRect:self.canvasVw.bounds toView:nil];
Boolean viewsOverlap = CGRectContainsRect(boundsB,boundsA );
if (viewsOverlap==YES) {
NSLog(@"intersects");
[touch.view setFrame:frame];
}
else{
NSLog(@"not intersects");
}
}
}
代码中的问题是假设我拖动 View ,它超出了该区域,然后就不再拖动了。
看图片:-
我需要仅将红色 View 拖动到白色区域而不是黑色区域。 请建议我如何做到这一点。 谢谢。
最佳答案
嗯,基本上是边界。尽管看起来很无聊,但请确保:
- 红色的 self.frame.position.x 不 < 0(零是其父级的位置)
- self.frame.position.x + self.frame.size.width 不大于 self.superview.size.width
Y 的逻辑相同。
编辑 1:
double possibleNewX = pt.x - startLocation.x;
if (((self.frame.position.x + possibleNewX) > 0) && ((self.frame.size.width + self.frame.position.x + possibleNewX) < self.superview.frame.size.width))
{
frame.origin.x += possibleNewX;
}
double possibleNewY = pt.y - startLocation.y;
if (((self.frame.position.y + possibleNewY) > 0) && ((self.frame.size.height + self.frame.position.y + possibleNewY) < self.superview.frame.size.width))
{
frame.origin.y += possibleNewY;
}
关于iphone - 在有限的边界内拖动 View 而不超出该边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13365964/