2016-04-19 36 views
0

我有一個UIView主視圖控制器裏面包含1 imageview.i移動imageview與此方法。如何在移動ImageView時保持UIView內的imageview?

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *aTouch = [touches anyObject]; 
    if (aTouch.view == self.sub_View) { 
    CGPoint location = [aTouch locationInView:self.sub_View]; 
    CGPoint previousLocation = [aTouch previousLocationInView:self.sub_View]; 
    self.imageView.frame = CGRectOffset(self.imageView.frame, (location.x - previousLocation.x), (location.y - previousLocation.y)); 
    } 
} 

Imageview move perfect。但是當我移動時,我必須保持UIView內的imageview。此代碼的問題是,當我移動ImageView時,它也移動到UIView之外。我必須保持UIView裏面的圖像和只能在UIView內移動。 請幫我解決這個問題。如何爲imageview設置邊界,以便它只能在UIView內部移動。

+0

是什麼self.sub_View –

+0

它是主視圖一個UIView包含imageview的 –

回答

0

試試下面的代碼。

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *aTouch = [touches anyObject]; 
    if (aTouch.view == self.sub_View) { 
    CGPoint location = [aTouch locationInView:self.sub_View]; 
    CGPoint previousLocation = [aTouch previousLocationInView:self.sub_View]; 
    CGRect newFrame = CGRectOffset(self.imageView.frame, (location.x - previousLocation.x), (location.y - previousLocation.y)); 
    if(newFrame.origin.x < 0) 
     newFrame.origin.x = 0; 
    if(newFrame.origin.y < 0) 
     newFrame.origin.y = 0; 
    if(newFrame.origin.x + newFrame.size.width > self.frame.size.width) 
     newFrame.origin.x = self.frame.size.width - self.imageView.frame.size.width; 
    if(newFrame.origin.y + newFrame.size.height > self.frame.size.height) 
     newFrame.origin.y = self.frame.size.height - self.imageView.frame.size.height; 

    self.imageView.frame = newFrame; 

    } 
} 
+0

現在移動是在Uiview裏面,但是當我放大imageview它會重置imagevuew框架,當你滾動它將隱藏圖像。 –

+0

你的意思是self.frame.size.width? –

0

一)您可以設置UIViewYES

B的clipsToBounds屬性)可以使用休耕代碼,將您UIImageView

self.imageView.center = CGPointMake(MAX(0.0, MIN(location.x - previousLocation.x, self.sub_View.bounds.size.width)), MAX(0.0, MIN(location.y - previousLocation.y, self.sub_View.bounds.size.height))); 
+0

保持它的ImageView在左上角後imageview的逗留後第一個舉動。 –