iOS实现UIButton的拖拽功能

2022-08-05 15:12:36

本文实例为大家分享了iOS实现UIButton拖拽功能的具体代码,供大家参考,具体内容如下在APP界面中,把资讯等功能设置为悬浮的Button并且能够让用户自己拖拽调整位置很常用。这里实现一下上述的功...

本文实例为大家分享了IOS实现UIButton拖拽功能的具体代码,供大家参考,具体内容如下

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

iOS实现UIButton的拖拽功能

这里给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 == UIGestphpureRecognizerStateChanged){
    //实时设置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 || bupythontton.center.y <=100 || button.center.y >=Height-100){
      [recognizer setState:UIGestureRecognizerStateEnded];
    }
   
  }else if(recognizer.state == UIGestureRecognphpizerStateEnded){
    //得到结束时button的center
    //根据center 判断应该的X和Y
    CGFloat n编程ewX=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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。