基于如何添加触摸并在视图上检测 UIImageView 以便我可以移动它而不是在它上面添加一个?
我检查了 CGRectIntersectsRect 单个 uiimageview。我需要如何检查多个 uiimageview?
正确的
错误的
-(void)initImagesAndGesture
{
UIImage *img = [UIImage imageNamed:@"beer.png"];
imgView1 = [[UIImageView alloc]initWithImage:img];
[imgView1 setFrame:CGRectMake(0, 0, 75, 115)];
[imgView1 setUserInteractionEnabled:YES];
UIPanGestureRecognizer *recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
[imgView1 addGestureRecognizer:recognizer1];
[self.view addSubview:imgView1];
img = [UIImage imageNamed:@"cups.png"];
imgView2 = [[UIImageView alloc]initWithImage:img];
[imgView2 setFrame:CGRectMake(200, 240, 64, 75)];
[imgView2 setUserInteractionEnabled:YES];
recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
[imgView2 addGestureRecognizer:recognizer1];
[self.view addSubview:imgView2];
}
-(void)handlePan1:(UIPanGestureRecognizer *)recognizer
{
if (!(CGRectIntersectsRect(imgView1.frame, imgView2.frame)))
{
CGPoint pre_moveLocation = [recognizer locationInView:recognizer.view];
NSLog(@"previous location %@",NSStringFromCGPoint(pre_moveLocation));
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:recognizer.view];
}
else
{
NSLog(@"intersect!");
CGPoint pre_moveLocation = [recognizer locationInView:recognizer.view];
NSLog(@"previous location %@",NSStringFromCGPoint(pre_moveLocation));
recognizer.view.center = CGPointMake(pre_moveLocation.x, pre_moveLocation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:recognizer.view];
//[imgView2 setFrame:CGRectMake(200, 240, 64, 75)];
//[imgView1 setFrame:CGRectMake(0, 0, 75, 115)];
}
}
-(void)addImgView:(UIPanGestureRecognizer *)recognizer
{
NSLog(@"tappppp");
UIImage *img = [UIImage imageNamed:@"beer.png"];
UIImageView *imgView = [[UIImageView alloc]initWithImage:img];
CGPoint tapLocation = [recognizer locationInView:recognizer.view];
[imgView setCenter:CGPointMake(tapLocation.x,tapLocation.y)];
[imgView setUserInteractionEnabled:YES];
UIPanGestureRecognizer *recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
[imgView addGestureRecognizer:recognizer1];
[self.view addSubview:imgView];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initImagesAndGesture];
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addImgView:)];
tapRecognizer.numberOfTapsRequired = 2;
tapRecognizer.numberOfTouchesRequired = 1;
[tapRecognizer setDelegate:self];
self.view.userInteractionEnabled = YES;
[self.view addGestureRecognizer:tapRecognizer];
}