iOS拖拽功能
XXJcanbethebest 人气:0在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
加载全部内容