UI基础 小球拖拽

root.m

#import "RootViewController.h"
#import "BallView.h"
@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //小球拖拽效果
    BallView *view=[[BallView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    view.backgroundColor =[UIColor redColor];
    view.layer.cornerRadius=50;
    view.layer.masksToBounds=YES;
    [self.view addSubview:view];
    
    
    
    

}

@end

ballView.m

#import "BallView.h"

@implementation BallView

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //这个方法里面获取起点
    //获取触摸对象
    UITouch * touch=[touches anyObject];
    //找到点击的点
    self.startPoint=[touch locationInView:self];
    
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //在这个方法里面让小球动起来
    //获取触摸对象
    UITouch* touch=[touches anyObject];
    //获取移动中的点
    CGPoint newPoint =[touch locationInView:self];
    //计算x y 分别移动多少
    CGFloat dx = newPoint.x - self.startPoint.x;
    CGFloat dy= newPoint.y - self.startPoint.y;
    //改变 小球位置
    self.center = CGPointMake(self.center.x+dx, self.center.y+dy);
    
    
    
}




@end

猜你喜欢

转载自www.cnblogs.com/zhangqing979797/p/13379019.html
今日推荐