2012-02-24 168 views
0

我正在嘗試拖動圖像視圖。我這樣做有一點成功,但它不像我想要的那樣行事。我希望它只能在圖像內部觸摸並拖動它時纔會移動。 但即使我在屏幕上的任何地方觸摸並拖動,它也在移動。拖動圖像視圖

我寫這樣的代碼:

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

}

+0

你爲什麼與'subviews'訪問?您可以聲明imageview的實例。並通過使用'CGRectContainsPoint'檢查你是否觸摸過imageview。 – Ilanchezhian 2012-02-24 05:53:39

+0

touchesBegin你可以檢查你的觸摸點是否在你的圖像視圖 – Bonny 2012-02-24 05:55:05

+0

您的圖像視圖的框架設置爲覆蓋整個屏幕? – 2012-02-24 05:57:21

回答

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

其工作。一些修改:框架不是一個屬性,所以發送它作爲一個message.and在if條件替換幀與targetFrame.Thanks! – condinya 2012-02-24 06:04:30

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