码迷,mamicode.com
首页 > 其他好文 > 详细

可以拖动的View

时间:2016-02-23 11:15:14      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

定义一个继承自UIview的类(即我们要移动的视图)

BallView.h

1 @interface BallView : UIView
2 {
3     CGPoint startPoint;
4 }
5 @end

BallView.m

 1 @implementation BallView
 2 
 3 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 4 {
 5     // 获取触摸对象
 6     UITouch *touch = [touches anyObject];
 7     startPoint = [touch locationInView:self];
 8 }
 9 
10 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
11 {
12     //获取触摸的对象
13     UITouch *touch = [touches anyObject];
14     CGPoint newPoint = [touch locationInView:self];
15     // 分别计算x y变动的距离
16     CGFloat dx = newPoint.x - startPoint.x;
17     CGFloat dy = newPoint.y - startPoint.y;
18     
19     // 改变中心点坐标
20     self.center = CGPointMake(self.center.x + dx, self.center.y + dy);
21 }
22 
23 @end

接下来我们在根视图控制器中引入头文件,初始化加入视图即可

1 - (void)viewDidLoad {
2     [super viewDidLoad];
3     
4     BallView *ball = [[BallView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
5     ball.backgroundColor = [UIColor redColor];
6     ball.layer.cornerRadius = ball.frame.size.width / 2;
7     ball.layer.masksToBounds = YES;
8     [self.view addSubview:ball];
9 }

 

可以拖动的View

标签:

原文地址:http://www.cnblogs.com/bishuai/p/5209067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!