iOS實現應用懸浮窗效果
本文實例為大傢分享瞭iOS實現應用懸浮窗效果的具體代碼,供大傢參考,具體內容如下
需求
在一個app應用的最頂部添加一個懸浮窗,就像ios系統AssistiveTouch 可以左右滑動,但是最終會停在左邊或右邊。
實現思路
在應用的視圖的最頂層添加一個UIWindow,用這個UIWindow 充當懸浮窗,給UIWindow添加移動的手勢監聽,讓懸浮窗隨著手指移動,釋放的時候,讓它以動畫的方式靠邊
代碼
//懸浮窗測試 //創建一個懸浮窗口 mwindow = [[AssistiveTouch alloc]initWithFrame:CGRectMake(100, 200, 40, 40) imageName:@"1.png"]; //ios9 window要設置rootview 不然崩潰 UIViewController *controller = [[UIViewController alloc] init]; mwindow.rootViewController = controller; //展示懸浮窗。。 [self.window makeKeyAndVisible];
//添加移動的手勢 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(locationChange:)]; pan.delaysTouchesBegan = YES; [self addGestureRecognizer:pan];
//改變位置 -(void)locationChange:(UIPanGestureRecognizer*)p { //[[UIApplication sharedApplication] keyWindow] CGPoint panPoint = [p locationInView:[[UIApplication sharedApplication] keyWindow]]; if(p.state == UIGestureRecognizerStateBegan) { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(changeColor) object:nil]; _imageView.alpha = 0.8; } else if (p.state == UIGestureRecognizerStateEnded) { [self performSelector:@selector(changeColor) withObject:nil afterDelay:4.0]; } if(p.state == UIGestureRecognizerStateChanged) { self.center = CGPointMake(panPoint.x, panPoint.y); } else if(p.state == UIGestureRecognizerStateEnded) { if(panPoint.x <= kScreenWidth/2) { if(panPoint.y <= 40+HEIGHT/2 && panPoint.x >= 20+WIDTH/2) { [UIView animateWithDuration:0.2 animations:^{ self.center = CGPointMake(panPoint.x, HEIGHT/2); }]; } else if(panPoint.y >= kScreenHeight-HEIGHT/2-40 && panPoint.x >= 20+WIDTH/2) { [UIView animateWithDuration:0.2 animations:^{ self.center = CGPointMake(panPoint.x, kScreenHeight-HEIGHT/2); }]; } else if (panPoint.x < WIDTH/2+15 && panPoint.y > kScreenHeight-HEIGHT/2) { [UIView animateWithDuration:0.2 animations:^{ self.center = CGPointMake(WIDTH/2, kScreenHeight-HEIGHT/2); }]; } else { CGFloat pointy = panPoint.y < HEIGHT/2 ? HEIGHT/2 :panPoint.y; [UIView animateWithDuration:0.2 animations:^{ self.center = CGPointMake(WIDTH/2, pointy); }]; } } else if(panPoint.x > kScreenWidth/2) { if(panPoint.y <= 40+HEIGHT/2 && panPoint.x < kScreenWidth-WIDTH/2-20 ) { [UIView animateWithDuration:0.2 animations:^{ self.center = CGPointMake(panPoint.x, HEIGHT/2); }]; } else if(panPoint.y >= kScreenHeight-40-HEIGHT/2 && panPoint.x < kScreenWidth-WIDTH/2-20) { [UIView animateWithDuration:0.2 animations:^{ self.center = CGPointMake(panPoint.x, 480-HEIGHT/2); }]; } else if (panPoint.x > kScreenWidth-WIDTH/2-15 && panPoint.y < HEIGHT/2) { [UIView animateWithDuration:0.2 animations:^{ self.center = CGPointMake(kScreenWidth-WIDTH/2, HEIGHT/2); }]; } else { CGFloat pointy = panPoint.y > kScreenHeight-HEIGHT/2 ? kScreenHeight-HEIGHT/2 :panPoint.y; [UIView animateWithDuration:0.2 animations:^{ self.center = CGPointMake(320-WIDTH/2, pointy); }]; } } } }
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。