拖动图像视图

时间:2012-02-24 05:47:39

标签: iphone cocoa-touch drag-and-drop uiimageview

我正在尝试拖动图片视图。我这样做有一点点成功,但它不是我想要的表现。我希望它只有在触摸图像内部并拖动它时才会移动。 但即使我从屏幕上的任何地方触摸和拖动它也会移动。

我写了这样的代码:

  -(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];

}

2 个答案:

答案 0 :(得分:2)

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...
}

答案 1 :(得分:0)

尝试这样的事情:

-(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];