您的位置:首页 > 移动开发 > IOS开发

iOS-悬浮按钮

2016-07-11 11:55 615 查看
在项目中可能会有这种需求,即在一个界面最顶层需要一个按钮,这个按钮可能是发布信息功能,也可能是回到顶部.这样我们可以使用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];

//添加悬浮按钮方式一(直接添加):
//  _button.frame = CGRectMake(screenWidth*0.5-28, screenHeight-74, 56, 56);
//  [_button addTarget:self action:@selector(suspendBtnClick) forControlEvents:UIControlEventTouchUpInside];
//[self.view addSubview:_button];
//[self.view bringSubviewToFront:_button];

//添加悬浮按钮方式二:(利用UIWindow)
_button.frame = CGRectMake(0,0, 56, 56);
[_button addTarget:self action:@selector(suspendBtnClick) forControlEvents:UIControlEventTouchUpInside];

//悬浮按钮所处的顶端UIWindow
_window = [[UIWindow alloc] initWithFrame:CGRectMake(screenWidth*0.5-28, screenHeight-54, 56, 56)];
//使得新建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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: