拖动图像视图
问题描述:
我正在尝试拖动图像视图。我这样做有一点成功,但它不像我想要的那样行事。我希望它只能在图像内部触摸并拖动它时才会移动。 但即使我在屏幕上的任何地方触摸并拖动,它也在移动。拖动图像视图
我写这样的代码:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//retrieve touch point
CGPoint pt= [[ touches anyObject] locationInView:[self.view.subviews objectAtIndex:0]];
startLocation = pt;
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
CGPoint pt = [[touches anyObject] locationInView: [self.view.subviews objectAtIndex:0]];
CGRect frame = [[self.view.subviews objectAtIndex:0]frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[[self.view.subviews objectAtIndex:0] setFrame: frame];
}
答
locationInView方法的返回值是相对于所述视图帧点。首先检查它是否在视图框中。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGRect targetFrame = [self.view.subviews objectAtIndex:0].frame;
//retrieve touch point
CGPoint pt= [[ touches anyObject] locationInView:[self.view.subviews objectAtIndex:0]];
//check if the point in the view frame
if (pt.x < 0 || pt.x > targetFrame.size.width || pt.y < 0 || pt.y > targetFrame.size.height)
{
isInTargetFrame = NO;
}
else
{
isInTargetFrame = YES;
startLocation = pt;
}
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
if(!isInTargetFrame)
{
return;
}
//move your view here...
}
+0
其工作。一些修改:框架不是一个属性,所以发送它作为一个message.and在if条件替换帧与targetFrame.Thanks! – condinya 2012-02-24 06:04:30
答
尝试这样:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//retrieve touch point
startLocation = [[ touches anyObject] locationInView:self.view];
// Now here check to make sure that start location is within the frame of
// your subview [self.view.subviews objectAtIndex:0]
// if it is you need to have a property like dragging = YES
// Then in touches ended you set dragging = NO
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
CGPoint pt = [[touches anyObject] locationInView: [self.view.subviews objectAtIndex:0]];
CGRect frame = [[self.view.subviews objectAtIndex:0]frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[[self.view.subviews objectAtIndex:0] setFrame: frame];
你为什么与'subviews'访问?您可以声明imageview的实例。并通过使用'CGRectContainsPoint'检查你是否触摸过imageview。 – Ilanchezhian 2012-02-24 05:53:39
touchesBegin你可以检查你的触摸点是否在你的图像视图 – Bonny 2012-02-24 05:55:05
您的图像视图的框架设置为覆盖整个屏幕? – 2012-02-24 05:57:21