您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關iOS如何實現全局懸浮按鈕的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
具體內容如下
現在有很多app都做這個全局按鈕
如上面兩張圖的效果,完成一個全局懸浮的按鈕,而且不會劃出屏幕外
既然是全局,那寫在AppDelegate中
UIWindow是一種特殊的UIView,它相當于一塊畫框,而UIView相當于里面的畫布。通常在一個app中只會有一個UIWindow。
AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) UIButton *button; @end
AppDelegate.m
先button懶加載
- (UIButton*)button { if (!_button) { _button = [UIButton buttonWithType:UIButtonTypeCustom]; _button.frame = CGRectMake(258, 450, 60, 60);//初始在屏幕上的位置 [_button setImage:[UIImage imageNamed:@"bcl_btn_whole"] forState:UIControlStateNormal]; } return _button; }
然后將其加在window上,設置手勢
-(void)createButton{ if (!_button) { _window = [[UIApplication sharedApplication] keyWindow]; _window.backgroundColor = [UIColor whiteColor]; [_window addSubview:self.button]; UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget: self action:@selector(locationChange:)]; pan.delaysTouchesBegan = YES; [_button addGestureRecognizer:pan]; } }
這個呢是為了開機啟動兩秒后創(chuàng)建全局button
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self performSelector:@selector(createButton) withObject:nil afterDelay:2]; }
最關鍵的就是設置button不要劃出屏幕外
以下四個else if分別為屏幕的上下左右
設置一個標記值isOVer
如果超出屏幕范圍,糾正回來
-(void)locationChange:(UIPanGestureRecognizer*)p{ CGFloat HEIGHT=_button.frame.size.height; CGFloat WIDTH=_button.frame.size.width; BOOL isOver = NO; CGPoint panPoint = [p locationInView:[UIApplication sharedApplication].windows[0]]; CGRect frame = CGRectMake(panPoint.x, panPoint.y, HEIGHT, WIDTH); NSLog(@"%f--panPoint.x-%f-panPoint.y-", panPoint.x, panPoint.y); if(p.state == UIGestureRecognizerStateChanged){ _button.center = CGPointMake(panPoint.x, panPoint.y); } else if(p.state == UIGestureRecognizerStateEnded){ if (panPoint.x + WIDTH > KScreenWidth) { frame.origin.x = KScreenWidth - WIDTH; isOver = YES; } else if (panPoint.y + HEIGHT > KScreenHeight) { frame.origin.y = KScreenHeight - HEIGHT; isOver = YES; } else if(panPoint.x - WIDTH / 2< 0) { frame.origin.x = 0; isOver = YES; } else if(panPoint.y - HEIGHT / 2 < 0) { frame.origin.y = 0; isOver = YES; } if (isOver) { [UIView animateWithDuration:0.3 animations:^{ self.button.frame = frame; }]; }
感謝各位的閱讀!關于“iOS如何實現全局懸浮按鈕”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。