很多APP都要用的如tabelView
新版本@synthesize window = _window;
image.png
练习
- 1、在松手的时候判断哪张图片在左视图还是右视图
- 2、拖入imageView数组到View视图中转换坐标然后label计数
- 3、点击图片删除时添加了手势即必须打开用户交互功能实现
-
4、删除图片后label计数也相应减少
以下是代码
image.png
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *imageViews;
@property (weak, nonatomic) IBOutlet UILabel *leftLabel;
@property (weak, nonatomic) IBOutlet UILabel *rightLabel;
@property (weak, nonatomic) IBOutlet UIView *leftView;
@property (weak, nonatomic) IBOutlet UIView *rightView;
@property(nonatomic,strong)UIImageView *dragIV;
@end
@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
//判断p点 点击的是哪个图片
for(UIImageView *iv in self.imageViews){
if (CGRectContainsPoint(iv.frame, p)) {
//removeFromSuperview移除控件
//[iv removeFromSuperview];
UIImageView *dragIV = [[UIImageView alloc]initWithFrame:iv.frame];
dragIV.image = iv.image;
[self.view addSubview:dragIV];
self.dragIV = dragIV;
//imageView的交互要打来手势方法才能执行
dragIV.userInteractionEnabled = YES;
//创建点击手势
UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
[dragIV addGestureRecognizer:tap];
}
}
}
-(void)tapAction:(UITapGestureRecognizer*)tap{
if([tap.view.superview isEqual:self.leftView]){
//把点击的view删除
[tap.view removeFromSuperview];
self.leftLabel.text = @(self.leftView.subviews.count).stringValue;
}else{
//把点击的view删除
[tap.view removeFromSuperview];
self.rightLabel.text = @(self.rightView.subviews.count).stringValue;
}
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
self.dragIV.center = p;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
if (CGRectContainsPoint(self.leftView.frame, self.dragIV.center)) {
//得到相对于self.view的点
CGPoint oldCenter = self.dragIV.center;
//把相对于self.view的点转换成相对于leftView的点
CGPoint newCenter = [self.view convertPoint:oldCenter toView:self.leftView];
[self.leftView addSubview:self.dragIV];
self.dragIV.center = newCenter;
self.leftLabel.text = @(self.leftView.subviews.count).stringValue;
}else if(CGRectContainsPoint(self.rightView.frame, self.dragIV.center)) {
CGPoint oldCenter = self.dragIV.center;
//把相对于self.view的点转换成相对于leftView的点
CGPoint newCenter = [self.view convertPoint:oldCenter toView:self.rightView];
[self.rightView addSubview:self.dragIV];
self.dragIV.center = newCenter;
self.rightLabel.text = @(self.rightView.subviews.count).stringValue;
}else{//没有在view里松手
[self.dragIV removeFromSuperview];
}
self.dragIV = nil;
}
网友评论