1.创建根视图控制器
2.创建一个MyView的类继承于UIView
3.在MyView的.m里
//补上延展
@interface MyView()
//用来记录视图开始的坐标
@property(nonatomic,assign)CGPoint startPoint;
@end
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//集合里元素的个数
//NSLog(@"%ld",touches.count);
//获取集合里的对象
UITouch *touch=[touches anyObject];
//获取相应视图的当前位置
self.startPoint=[touch locationInView:self];
NSLog(@"%g",self.startPoint.x);
NSLog(@"%g",self.startPoint.y);
}
//通过移动找到变化,然后让MyView也进行相应的调整,从而实现视图随手移动的效果
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//获取触摸的对象
UITouch *touch=[touches anyObject];
//获取移动之后的坐标
CGPoint movePoint=[touch locationInView:self];
//找坐标的变化
CGFloat dx=movePoint.x-self.startPoint.x;
CGFloat dy=movePoint.y-self.startPoint.y;
//设置视图的移动变化
self.center=CGPointMake(self.center.x+dx, self.center.y+dy);
}
5.在根视图控制器里创建一个MyView的对象(注意引头文件)
MyView *myview=[[MyView alloc] initWithFrame:CGRectMake(100, 200, 100, 100)];
myview.backgroundColor=[UIColor orangeColor];
[self.view addSubview:myview];
[myview release];
myview.layer.cornerRadius=10;
myview.layer.borderWidth=1;