创建可移动的视图

来源:互联网 发布:知堂回想录下载 编辑:程序博客网 时间:2024/04/30 13:21

1.首先建立一个根视图控制器(引入头文件)

原代码:

 // 设置根视图控制器    MainViewController *mainVC=[[MainViewController alloc] init];    _window.rootViewController =mainVC;    [mainVC release];

2.在视图控制器中建立一个MyView的 UIView的子类(引入头文件)

原代码:

///创建一个MyView;    MyView *myView=[[MyView alloc] initWithFrame:CGRectMake(100, 200, 150, 40)];    myView.backgroundColor =[UIColor redColor];    [self.view addSubview:myView];    [myView release];

3.在MyView中创建一个方法

从上面的代码可以看出:

touches相当一个集合 点击一下 相当于集合中只有一个元素

4.在触摸开始方法中获取初始位置:

(1).用 touches.count 可以测出touches中元素的个数

 NSLog(@"%ld",touches.count);

(2).用 anyObject可以去到这个对象

UITouch *touch =[touches anyObject];

(3).通过触摸对象获取相应的视图的当前的位置

self.startPoint =[touch locationInView:self];   

5.在移动方法中可以得到新的点的坐标

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{    // 通过移动,找到变化,然后让MyView也进行相应的调整,从而实现试图随手移动的效果    // 获取触摸的对象    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);  }  
0 0
原创粉丝点击