UIView
内有UIImageView
和UIView
。我使用Touches方法拖动UIImageView
。
这很有效。我有一个问题。
当我触摸UIView中的任何地方时,我希望UIImageView
拖动或移动。目前,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 :(得分:1)
对不起,这是迟到的,但万一其他人需要帮助进行此更改,请查看此代码:
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView: touch.view];
"YOURVIEW".center = touchLocation;
基本上,您必须将事件设置为在视图的任何位置发生。
我希望这可以帮助那些人^ _ ^
答案 1 :(得分:0)
您将必须使UIView *subview
自定义类与touchesBegan:
等等进行覆盖。然后你需要制作你的UIImageView setUserInteractionEnabled:NO
。这样,您的自定义UIView
上的任何触摸事件都将由视图控制,您可以随意使用它或它的子视图(UIImageView
)。
您的UIView
子类必须在其类变量中包含您的UIImageView
,以便在触摸事件期间对其进行操作,但这很容易理解。