定义一个继承自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 }
时间: 2024-10-15 02:07:34