iOS开发——悬浮按钮
Posted qinxiaoguang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS开发——悬浮按钮相关的知识,希望对你有一定的参考价值。
项目中需要在创建一个悬浮按钮,自己觉得光创建一个按钮不能滑动有点不太优化,就自己试着做了一个可以随意拖动的悬浮按钮,希望大家能够多多支持。
-(void)viewDidLoad { //创建悬浮按钮 self.editEventsButton=[UIButton buttonWithType:UIButtonTypeCustom]; self.editEventsButton.frame=CGRectMake(0, 0, 60, 60); [self.editEventsButton setBackgroundImage:[UIImage imageNamed:@"问医生"] forState:UIControlStateNormal]; [self.editEventsButton addTarget:self action:@selector(gotoEditEvents) forControlEvents:UIControlEventTouchUpInside]; self.window=[[UIWindow alloc] initWithFrame:CGRectMake(ScreenWidth-55, ScreenHeight-75-CGRectGetHeight(self.chartView.frame), 60, 60)]; self.window.windowLevel=UIWindowLevelAlert+1; self.window.backgroundColor=[UIColor clearColor]; self.window.layer.cornerRadius=20; self.window.layer.masksToBounds=YES; [self.window addSubview:self.editEventsButton]; [self.window makeKeyAndVisible]; //放一个拖动手势,用来改变控件的位置 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changePostion:)]; [self.editEventsButton addGestureRecognizer:pan]; [self charts]; [self tabarTool]; } //手势事件 -- 改变位置 -(void)changePostion:(UIPanGestureRecognizer *)pan { CGPoint point = [pan translationInView:self.window]; CGFloat width = [UIScreen mainScreen].bounds.size.width; CGFloat height = [UIScreen mainScreen].bounds.size.height; CGRect originalFrame = self.window.frame; if (originalFrame.origin.x >= 0 && originalFrame.origin.x+originalFrame.size.width <= width) { originalFrame.origin.x += point.x; } if (originalFrame.origin.y >= 0 && originalFrame.origin.y+originalFrame.size.height <= height) { originalFrame.origin.y += point.y; } self.window.frame = originalFrame; [pan setTranslation:CGPointZero inView:self.view]; if (pan.state == UIGestureRecognizerStateBegan) { _editEventsButton.enabled = NO; }else if (pan.state == UIGestureRecognizerStateChanged){ } else { CGRect frame = self.window.frame; //记录是否越界 BOOL isOver = NO; if (frame.origin.x < 0) { frame.origin.x = 0; isOver = YES; } else if (frame.origin.x+frame.size.width > width) { frame.origin.x = width - frame.size.width; isOver = YES; } if (frame.origin.y < 0) { frame.origin.y = 0; isOver = YES; } else if (frame.origin.y+frame.size.height > height) { frame.origin.y = height - frame.size.height; isOver = YES; } if (isOver) { [UIView animateWithDuration:0.3 animations:^{ self.window.frame = frame; }]; } _editEventsButton.enabled = YES; } }
以上是关于iOS开发——悬浮按钮的主要内容,如果未能解决你的问题,请参考以下文章
iOS中全局悬浮按钮,类似IPhone中的AssistiveTouch (可以替换为视频悬浮窗口)