UI之把一个控件在屏幕内做任意拖拽并得到时时坐标

来源:互联网 发布:淘宝手机助手登陆失败 编辑:程序博客网 时间:2024/06/05 01:10

@interfaceViewController ()

{

    UIView *_view;

    UIImageView *_imageV;

}

@end

@implementationViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    _view = [[UIView alloc]initWithFrame:CGRectMake(100,100, 100, 100)];

    _view.backgroundColor = [UIColorpurpleColor];

    [self.view addSubview:_view];

    _imageV = [[UIImageViewalloc]initWithFrame:CGRectMake(100, 220, 100, 100)];

    _imageV.image = [UIImage imageNamed:@"blue"];

    //是否与用户交互  UIImageView默认是NO 想要交互设置为YES

    _imageV.userInteractionEnabled = YES;

    [self.view addSubview:_imageV];

}

//开始触摸

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    //touches 触摸的集合

    //当手指在屏幕上点击/滑动的时候都会生成触摸对象(UITouch)

    //集合里面就一个touch对象,可以使用anyObject拿出来

    UITouch *touch = [touches anyObject];

    //拿到触摸的时间

    NSTimeInterval time = touch.timestamp;

    NSLog(@"touch时间:%f",time);

    //点击多少次

    NSUInteger num = touch.tapCount;

    NSLog(@"第几次数:%ld",(unsignedlong)num);

    //事件(触摸)处于什么状态

    UITouchPhase phase = touch.phase;

    /*

     UITouchPhaseBegan,

     UITouchPhaseMoved,

     UITouchPhaseStationary,

     UITouchPhaseEnded,

     UITouchPhaseCancelled,

     */

    //拿到当前touch的视图控件

    UIView *view = touch.view;

    NSLog(@"当前touch的控件:%@",view);

    //previousLocationInView 拿到上一次touch的坐标

    CGPoint lastPoint = [touchpreviousLocationInView:view];

    //locationInView 拿到当前的touch的坐标

    CGPoint locaPoint = [touchlocationInView:view];

    NSLog(@"上一次坐标:%@ 当前坐标:%@",NSStringFromCGPoint(lastPoint),NSStringFromCGPoint(locaPoint));

}

//取消触摸(电话、短信....)

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{

}

//结束触摸

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    NSLog(@"触摸结束");

}

//移动触摸

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];

    UIView *view = touch.view;

    NSLog(@"moved当前touch的控件:%@",view);

    //previousLocationInView 拿到上一次touch的坐标

    CGPoint lastPoint = [touchpreviousLocationInView:view];

    //locationInView 拿到当前的touch的坐标

    CGPoint locaPoint = [touchlocationInView:view];

    NSLog(@"moved上一次坐标:%@ 当前坐标:%@",NSStringFromCGPoint(lastPoint),NSStringFromCGPoint(locaPoint));

    //位移的距离

    CGPoint point = CGPointMake(locaPoint.x-lastPoint.x, locaPoint.y - lastPoint.y);

    if (view == self.view) {

        NSLog(@"站住,不许动");

    }else{

       //通过偏移量重新设置view的center

       view.center = CGPointMake(view.center.x+ point.x, view.center.y + point.y);

    }

}


0 0
原创粉丝点击