iOS-悬浮按钮

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值