I am implementing a draggable UIView in my application. The codes I have worked fine but I would like to set a restricted area the UIView can be moved.
我在我的应用程序中实现了一个可拖动的UIView。我工作的代码很好,但我想设置一个限制区域UIView可以移动。
My codes:
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
if( [touch view] == camview)
{
CGPoint location = [touch locationInView:self.view;
startX = camview.center.x;
startY= location.y - camview.center.y;
}
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if( [touch view] == camview)
{
CGPoint location = [touch locationInView:self.view];
location.y =location.y - startY;
location.x = startX;
camview.center = location;
}
}
So how can I set the minimum and maximum y value that the UIView can be dragged?
那么如何设置UIView可以拖动的最小和最大y值?
Thanks!
1 个解决方案
#1
1
If you are interested in making sure the view frame doesn't go over or under a certain y value you could do the following,
如果您有兴趣确保视图框架没有超过或低于某个y值,您可以执行以下操作,
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGFloat minY, maxY; //The position in your self.view you are interested in
UITouch *touch = [[event allTouches] anyObject];
if( [touch view] == camview)
{
CGPoint location = [touch locationInView:self.view];
location.y = location.y - startY;
location.y = MIN(location.y,maxY); //Always <= maxY
location.y = MAX(location.y,minY); //Always >= minY
location.x = startX;
camview.center = location;
}
}
#1
1
If you are interested in making sure the view frame doesn't go over or under a certain y value you could do the following,
如果您有兴趣确保视图框架没有超过或低于某个y值,您可以执行以下操作,
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGFloat minY, maxY; //The position in your self.view you are interested in
UITouch *touch = [[event allTouches] anyObject];
if( [touch view] == camview)
{
CGPoint location = [touch locationInView:self.view];
location.y = location.y - startY;
location.y = MIN(location.y,maxY); //Always <= maxY
location.y = MAX(location.y,minY); //Always >= minY
location.x = startX;
camview.center = location;
}
}