首页 >> 大全

iOS 全局悬浮按钮

2023-10-01 大全 27 作者:考证青年

现在有很多app都做这个全局按钮

如上面两张图的效果,完成一个全局悬浮的按钮,而且不会划出屏幕

既然是全局,那写在中

是一种特殊的,它相当于一块画框,而相当于里面的画布。通常在一个app中只会有一个。

.h

ios全局悬浮窗口看视频__悬浮全屏是什么意思

@interface AppDelegate : UIResponder @property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UIButton *button;@end

.m

先懒加载

- (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;
}

然后将其加在上,设置手势

-(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];}
}

悬浮全屏是什么意思__ios全局悬浮窗口看视频

这个呢是为了开机启动两秒后创建全局

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[self performSelector:@selector(createButton) withObject:nil afterDelay:2];
}

最关键的就是设置不要划出屏幕外

以下四个else if分别为屏幕的上下左右

设置一个标记值

如果超出屏幕范围,纠正回来

-(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;}];}

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了