我在UIView
内部有UIView
和UIImageView
。我使用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;
}
问候
你在哪里覆盖的touchesBegan,touchesMoved ......,在UIView类或UIIamgeView类? –