标签:
在项目中可能会有这种需求,即在一个界面最顶层需要一个按钮,这个按钮可能是发布信息功能,也可能是回到顶部.这样我们可以使用UIwindow这个神奇的控件实现,很简单.
完整项目源码:
https://github.com/qxuewei/XWSuspendBtn
最终实现效果如下:
实现逻辑:
1.在需要出现悬浮按钮的类中声明按钮UIButton属性和UIWindow属性
/** window */
@property (nonatomic, strong) UIWindow *window;
/** 悬浮按钮 */
@property (nonatomic, strong) UIButton *button;
2.创建UIWindow以及悬浮按钮方法
-(void)creatSuspendBtn{
//悬浮按钮
_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setImage:[UIImage imageNamed:@"plus"] forState:UIControlStateNormal];
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
_button.frame = CGRectMake(0,0, 64, 64);
[_button addTarget:self action:@selector(suspendBtnClick) forControlEvents:UIControlEventTouchUpInside];
//悬浮按钮所处的顶端UIWindow
_window = [[UIWindow alloc] initWithFrame:CGRectMake(screenWidth*0.5-32, screenHeight-84, 64, 64)];
//使得新建window在最顶端
_window.windowLevel = UIWindowLevelAlert + 1;
_window.backgroundColor = [UIColor clearColor];
[_window addSubview:_button];
//显示window
[_window makeKeyAndVisible];
}
3.初始化视图时创建悬浮按钮
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.mainTableView setDelegate:self];
[self.mainTableView setDataSource:self];
//延时加载window,注意我们需要在rootWindow创建完成之后再创建这个悬浮的按钮
[self performSelector:@selector(creatSuspendBtn) withObject:nil afterDelay:0.2];
}
项目github地址:
https://github.com/qxuewei/XWSuspendBtn
标签:
原文地址:http://blog.csdn.net/qxuewei/article/details/51879736