2014-03-03 44 views
0

我在UIView内部有UIViewUIImageView。我使用Touches方法拖动UIImageView用触摸移动UIImageview在UIView中按下任意位置时移动IOS

This works great。但我有一个问题。

我想要UIImageView拖动或移动,当我触摸UIView中的任何地方。目前,这个UIImageview只能在触摸UIIMageView而不是UIView时移动。

self.scrollView.scrollEnabled = NO; 
UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(10, 135, 300, 200)]; 
subview.backgroundColor = [UIColor clearColor]; 

// Create an instance of the image to drag 
ImageToDrag *img2 = [[ImageToDrag alloc] initWithImage:[UIImage imageNamed:@"markit_btn.png"]]; 
img2.center = CGPointMake(110, 75); 
img2.userInteractionEnabled = YES; 
[subview addSubview:img2]; 
[self.view addSubview:subview]; 

我有一个单独的文件,其中包括我在UIView的位于在控制器的头文件。

- (id)initWithImage:(UIImage *)image 
{ 
if (self = [super initWithImage:image]) 
    self.userInteractionEnabled = YES; 
return self; 
} 

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
// When a touch starts, get the current location in the view 
currentPoint = [[touches anyObject] locationInView:self]; 
} 

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
// Get active location upon move 
CGPoint activePoint = [[touches anyObject] locationInView:self]; 

// Determine new point based on where the touch is now located 
CGPoint newPoint = CGPointMake(self.center.x + (activePoint.x - currentPoint.x), 
          self.center.y + (activePoint.y - currentPoint.y)); 

//-------------------------------------------------------- 
// Make sure we stay within the bounds of the parent view 
//-------------------------------------------------------- 
float midPointX = CGRectGetMidX(self.bounds); 
// If too far right... 
if (newPoint.x > self.superview.bounds.size.width - midPointX) 
    newPoint.x = self.superview.bounds.size.width - midPointX; 
else if (newPoint.x < midPointX)  // If too far left... 
    newPoint.x = midPointX; 

float midPointY = CGRectGetMidY(self.bounds); 
// If too far down... 
if (newPoint.y > self.superview.bounds.size.height - midPointY) 
    newPoint.y = self.superview.bounds.size.height - midPointY; 
else if (newPoint.y < midPointY) // If too far up... 
    newPoint.y = midPointY; 

// Set new center location 
self.center = newPoint; 
} 

问候

+0

你在哪里覆盖的touchesBegan,touchesMoved ......,在UIView类或UIIamgeView类? –

回答

0

你将不得不让你的UIView *subview定制类与touchesBegan:等重写。然后你需要制作你的UIImageView setUserInteractionEnabled:NO。这样,您的自定义UIView上的任何触摸事件都将由视图控制,您可以随心所欲地使用它或它的子视图(UIImageView)。

你的UIView子类将不得不包含你的UIImageView它的类变量,以便在触摸事件中操纵它,但这很容易弄清楚。

1

对不起,这是suuuper晚,但为了以防万一任何人的其他需要帮助这个变化,看看这个代码:

UITouch *touch = [[event allTouches] anyObject]; 
CGPoint touchLocation = [touch locationInView: touch.view]; 
"YOURVIEW".center = touchLocation; 

基本上,你必须设置该事件的看法发生在任何地方。

我希望这有助于有人出来^ _^

相关问题