可以拖动的View

定义一个继承自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 }

 

转载于:https://www.cnblogs.com/bishuai/p/5209067.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值