如何添加触摸和检测视图上的UIImageView所以我可以移动它而不是在它上面添加一个? [英] how to add on touch and detect UIImageView on view so i could move it around and not adding one on top of it?
问题描述
我想知道你们是否有一个示例代码添加并在触摸时移动UIImageView并检测是否有UIImageView,所以我无法在其上添加UIImageView。
i wonder if you guys have a sample code adding and move UIImageView on touch and also detect if there is an UIImageView there so i can't add UIImageView on top of it.
编辑:更清晰的问题
1.我想在触摸视图时添加一个杯子(UIImageView)但是不要将杯子(UIImageView)放到堆叠中。
clearer question 1. i wanna add an cups(UIImageView) when i touch the view but do not wan the cup(UIImageView) to stack.
- 我想移动UIImageView但是如果那里有UIImageView那么它会弹回到原来的位置,所以它不会在那里堆叠UIImageView。
感谢您阅读我的问题并感谢您的帮助
thanks for reading my question and appreciated your helps
欢呼
des
推荐答案
这应该让你去......
This should let you going…
在头文件中创建两个ivars:
Create two ivars in your header file:
UIImageView *myImageView1;
UIImageView *myImageView2;
接下来的两种方法将在您的实施文件中:
The next two methods will be in your implementation file:
-(void)initImagesAndPanGesture
{
UIImage *img = [UIImage imageNamed:@"image1.png"];
myImageView1 = [[UIImageView alloc]initWithImage:img];
[myImageView1 setFrame:CGRectMake(300, 800, 100, 100)];
[myImageView1 setUserInteractionEnabled:YES];
UIPanGestureRecognizer *recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
[myImageView1 addGestureRecognizer:recognizer1];
[self.view addSubview:myImageView1];
img = [UIImage imageNamed:@"image2.png"];
myImageView2 = [[UIImageView alloc]initWithImage:img];
[myImageView2 setFrame:CGRectMake(500, 800, 100, 100)];
[myImageView2 setUserInteractionEnabled:YES];
recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
[myImageView2 addGestureRecognizer:recognizer1];
[self.view addSubview:myImageView2];
}
-(void)handlePan1:(UIPanGestureRecognizer *)recognizer
{
if (!(CGRectIntersectsRect(myImageView1.frame, myImageView2.frame)))
{
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:self.view];
}
else
{
NSLog(@"intersect!");
}
}
这篇关于如何添加触摸和检测视图上的UIImageView所以我可以移动它而不是在它上面添加一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!