iOS實現(xiàn)UIButton的拖拽功能
本文實例為大家分享了iOS實現(xiàn)UIButton拖拽功能的具體代碼,供大家參考,具體內(nèi)容如下
在APP界面中,把資訊等功能設置為懸浮的Button并且能夠讓用戶自己拖拽調(diào)整位置很常用。這里實現(xiàn)一下上述的功能,我們先看一下效果圖

這里給UIButton的拖拽的范圍進行了設定,超過了這個區(qū)域則強行結(jié)束拖拽。
我們知道UIButton是自帶手勢事件的,但我們不選擇使其自帶的手勢事件來響應拖拽,其原因為自帶的手勢不好得到和控制拖拽的狀態(tài)。我們創(chuàng)建一個 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];
? ??
}然后我們實現(xiàn) movingBtn
-(void)movingBtn:(UIPanGestureRecognizer *)recognizer{
? ? //得到拖拽的UIButton
? ? UIButton *button = (UIButton *)recognizer.view;
? ? //得到拖拽的偏移量
? ? CGPoint translation = [recognizer translationInView:button];
? ??
? ? //對拖拽事件的狀態(tài)進行判斷 也就是選擇自定義手勢的原因
? ? 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的位置進行判斷,超出范圍則強行使拖拽事件結(jié)束
? ? ? ? //這個范圍可以自己自定義
? ? ? ? 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){
? ? ? ? //得到結(jié)束時button的center
? ? ? ? //根據(jù)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];
? ? }
}至此 我們就實現(xiàn)了可拖拽的UIButton
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
iOScollectionView廣告無限滾動實例(Swift實現(xiàn))
本篇文章主要介紹了iOScollectionView廣告無限滾動實例,可以實現(xiàn)廣告無限滾動,有興趣的可以了解一下。2016-11-11
iOS中在APP內(nèi)加入AppStore評分功能的實現(xiàn)方法
這篇文章主要介紹了iOS中在APP內(nèi)加入AppStore評分功能的實現(xiàn)方法,文中筆者給大家整理了三種方式,大家可以根據(jù)自己的需求選擇,需要的朋友可以參考下2017-11-11

