IOS图片和按钮在屏幕中随意拖动

IOS图片和按钮在屏幕中随意拖动

1、先给图片添加手势

 //创建一个拖动的手势

    UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];

    [self.picImg setUserInteractionEnabled:YES];//开启图片控件的用户交互

    [self.picImg addGestureRecognizer:pan];//给图片添加手势


2、拖动时,执行手势的方法,更改图片的中心点即可,如果是按钮同理

#pragma mark - 手势执行的方法

-(void)handlePan:(UIPanGestureRecognizer *)rec{


    //返回在横坐标上、纵坐标上拖动了多少像素

    CGPoint point=[rec translationInView:self.view];

    NSLog(@"%f,%f",point.x,point.y);

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

    //拖动完之后,每次都要用setTranslation:方法制0这样才不至于不受控制般滑动出视图

    [rec setTranslation:CGPointMake(0, 0) inView:self.view];


}


---------------------------

有网友反馈会拖到屏幕外面去,根据上面的第2点进行了改进,控制了中心点的位置,代码见如下:
//拖动时,执行手势的方法,更改图片的中心点即可,如果是按钮同理
#pragma mark - 手势执行的方法
-(void)handlePan:(UIPanGestureRecognizer *)rec{
    
    CGFloat KWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat KHeight = [UIScreen mainScreen].bounds.size.height;
    
    //返回在横坐标上、纵坐标上拖动了多少像素
    CGPoint point=[rec translationInView:self.view];
    NSLog(@"%f,%f",point.x,point.y);
    
    CGFloat centerX = rec.view.center.x+point.x;
    CGFloat centerY = rec.view.center.y+point.y;
    
    CGFloat viewHalfH = rec.view.frame.size.height/2;
    CGFloat viewhalfW = rec.view.frame.size.width/2;
    
    //确定特殊的centerY
    if (centerY - viewHalfH < 0 ) {
        centerY = viewHalfH;
    }
    if (centerY + viewHalfH > KHeight ) {
        centerY = KHeight - viewHalfH;
    }
    
    //确定特殊的centerX
    if (centerX - viewhalfW < 0){
        centerX = viewhalfW;
    }
    if (centerX + viewhalfW > KWidth){
        centerX = KWidth - viewhalfW;
    }
    
    rec.view.center=CGPointMake(centerX, centerY);
    
    //拖动完之后,每次都要用setTranslation:方法制0这样才不至于不受控制般滑动出视图
    [rec setTranslation:CGPointMake(0, 0) inView:self.view];
    
}

你可能感兴趣的:(IOS学习)