经过Google搜索并仍未找到任何解决方案后,我问了一个问题。
我的问题是: - 我想在特定区域拖动我的视图,除此之外,我不希望我的视图拖动但它应该在指定的视图中可拖动。 我能够实现停止拖动,如果拖动超出但是当我触摸它以拖动它不会拖动的允许区域时。
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");
}
}
}
代码中的问题是假设我拖动视图,然后它移出区域,然后再不拖动。
见图: -
我需要将红色视图仅拖动到白色区域而不是黑色区域。 请建议我如何做到这一点。 感谢。
答案 0 :(得分:1)
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;
}