iOS实现UIButton的拖拽功能

iOS实现UIButton的拖拽功能,第1张

在APP界面中,把资讯等功能设置为悬浮的Button并且能够让用户自己拖拽调整位置很常用。这里实现一下上述的功能,我们先看一下效果图

这里给UIButton的拖拽的范围进行了设定,超过了这个区域则强行结束拖拽。


我们知道UIButton是自带手势事件的,但我们不选择使其自带的手势事件来响应拖拽,其原因为自带的手势不好得到和控制拖拽的状态。我们创建一个 UIPanGestureRecognizer 添加给UIButton

- (void)viewDidLoad {
    [super viewDidLoad];
    Width=[UIScreen mainScreen].bounds.size.width;
    Height=[UIScreen mainScreen].bounds.size.height;
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(10, 200, 60, 60)];
    btn.backgroundColor=[UIColor blueColor];
    [btn setTitle:@"B" forState:UIControlStateNormal];
    //UIPanGestureRecognizer手势
    UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(movingBtn:)];
    [btn addGestureRecognizer:pan];
    
    [self.view addSubview:btn];
    
}

然后我们实现 movingBtn

-(void)movingBtn:(UIPanGestureRecognizer *)recognizer{
    //得到拖拽的UIButton
    UIButton *button = (UIButton *)recognizer.view;
    //得到拖拽的偏移量
    CGPoint translation = [recognizer translationInView:button];
    
    //对拖拽事件的状态进行判断 也就是选择自定义手势的原因
    if(recognizer.state == UIGestureRecognizerStateBegan){
        
    }else if(recognizer.state == UIGestureRecognizerStateChanged){
        //实时设置button的center、recognizer
        button.center = CGPointMake(button.center.x + translation.x, button.center.y + translation.y);
        [recognizer setTranslation:CGPointZero inView:button];

        //对button的位置进行判断,超出范围则强行使拖拽事件结束
        //这个范围可以自己自定义
        if(button.center.x <= 40 || button.center.x>=Width-40 || button.center.y <=100 || button.center.y >=Height-100){
            [recognizer setState:UIGestureRecognizerStateEnded];
        }
        
    }else if(recognizer.state == UIGestureRecognizerStateEnded){
        //得到结束时button的center
        //根据center 判断应该的X和Y
        CGFloat newX=button.center.x;
        if(button.center.x <=Width/2) newX=40;
        else if(button.center.x >=Width/2) newX=Width-40;
        
        CGFloat newY=button.center.y;
        if(button.center.y <=100) newY=100;
        else if(button.center.y >=Height-100) newY=Height-100;
        
        button.center = CGPointMake(newX, newY);
        [recognizer setTranslation:CGPointZero inView:button];
    }
}

至此 我们就实现了可拖拽的UIButton

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/997017.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存