//开始触摸
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// NSSet集合 和数组类似 都是用来装多个对象的 但是区别是set无序
//获取set集合中任意对象
[touches anyObject];
//把set集合转成array数组
NSArray *arr = touches.allObjects;
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
NSLog(@"x=%f y=%f",p.x,p.y);
NSLog(@"%@",NSStringFromCGPoint(p));
//便利所有图片
for (UIImageView *iv in self.imageViews) {
//判断触碰的是哪一个图片
if (CGRectContainsPoint(iv.frame, p)) {
//将触碰的图片变为属性,让移动触摸位置方法等方法可以调用
self.dragView = iv;
break;
}
}
}
//移动触摸位置
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
//让触摸图片的中心位置等于触摸的位置
self.dragView.center = p;
}
//结束触摸
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
NSLog(@"end%@",NSStringFromCGPoint(p));
//结束触摸时,解除touch的坐标与图片的绑定
self.dragView = nil;
}
//当发生意外中断时如有电话进来
-(void)touchesCancelled:(NSSt *)touches withEvent:(UIEvent *)event{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
NSLog(@"Cancell%@",NSStringFromCGPoint(p));
}
将控件从原来父视图self.view移动到新的父视图self.leftView,坐标偏移值修正方法
//当父视图发生改变的时候需要把相对于原来父视图的坐标转换成相对于新父视图的坐标
CGPoint oldCenter = self.dragView.center;
CGPoint newCenter = [self.view convertPoint:oldCenter toView:self.leftView];
[self.leftView addSubview:self.dragView];
self.dragView.center = newCenter;
记录添加到视图中控件的个数
通过视图子视图数组中中项目的个数
self.rightLabel.text = [NSString stringWithFormat:@"%d",self.rightView.subviews.count];
让超出视图边缘的部分不显示
storyboard中选中视图属性中Drawing中的Clip SubSubviews勾选