iOS實現(xiàn)UIButton的拖拽功能
本文實例為大家分享了iOS實現(xiàn)UIButton拖拽功能的具體代碼,供大家參考,具體內(nèi)容如下
在APP界面中,把資訊等功能設(shè)置為懸浮的Button并且能夠讓用戶自己拖拽調(diào)整位置很常用。這里實現(xiàn)一下上述的功能,我們先看一下效果圖
這里給UIButton的拖拽的范圍進行了設(shè)定,超過了這個區(qū)域則強行結(jié)束拖拽。
我們知道UIButton是自帶手勢事件的,但我們不選擇使其自帶的手勢事件來響應(yīng)拖拽,其原因為自帶的手勢不好得到和控制拖拽的狀態(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){ ? ? ? ? //實時設(shè)置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 判斷應(yīng)該的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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
iOScollectionView廣告無限滾動實例(Swift實現(xiàn))
本篇文章主要介紹了iOScollectionView廣告無限滾動實例,可以實現(xiàn)廣告無限滾動,有興趣的可以了解一下。2016-11-11學(xué)習(xí)iOS開關(guān)按鈕UISwitch控件
這篇文章主要為大家詳細介紹了iOS開關(guān)按鈕UISwitch控件,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-08-08iOS中在APP內(nèi)加入AppStore評分功能的實現(xiàn)方法
這篇文章主要介紹了iOS中在APP內(nèi)加入AppStore評分功能的實現(xiàn)方法,文中筆者給大家整理了三種方式,大家可以根據(jù)自己的需求選擇,需要的朋友可以參考下2017-11-11iOS開發(fā)網(wǎng)絡(luò)編程之?dāng)帱c續(xù)傳
在下載較大的文件的時候,一次不能下載完畢,這就需要用到斷點續(xù)傳,那么在IOS開發(fā)中該如何實現(xiàn)呢,下面跟著小編一起通過本文來學(xué)習(xí)下。2016-08-08