Tai Chi's Blog

专注于移动开发

利用UIWindow创建悬浮按钮


创建全局属性

@property(strong,nonatomic)UIWindow *giftWindow;
@property(strong,nonatomic)UIButton *giftBtn;
@property (strong,nonatomic) UIImageView *giftImgView;

创建按钮,window,imageView

- (void)giftButton {

    _giftWindow = [[UIWindow alloc]initWithFrame:CGRectMake(WIDTH-85, 30, 85, 85)];
    _giftWindow.windowLevel = UIWindowLevelAlert + 1;
    [_giftWindow makeKeyAndVisible];//关键语句,显示window

    _giftImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 85, 85)];

    // 创建序列帧动画
    NSMutableArray *array = [NSMutableArray array];

    for (int i = 0; i < 7; i++) {
        NSString *imageName = [NSString stringWithFormat:@"lihe-%d", i + 1];
        UIImage *image = [UIImage imageNamed:imageName];

        // 把图片添加到数组中
        [array addObject:image];
    }

    self.giftImgView.animationImages = array;
    self.giftImgView.animationDuration = 1.5;
    self.giftImgView.animationRepeatCount = 0;    // 0 表示重复
    [self.giftImgView startAnimating];
    [_giftWindow addSubview:_giftImgView];

    _giftBtn = [[UIButton alloc] init];
    _giftBtn.backgroundColor = [UIColor clearColor];
    [_giftBtn addTarget:self action:@selector(giftBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _giftBtn.frame = CGRectMake(0, 0, 85, 85);
    [_giftWindow addSubview:_giftBtn];

}

实现点击

- (void)giftBtnClick{
    NSLog(@"111");

    //让window消失
    [_giftWindow resignKeyWindow];
    _giftWindow = nil;   
}

PS:因为是新创建了一个window,所以跳到其他见面时也会有,如果不想让其他页面显示需要在viewDidDisappear里写

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_giftWindow resignKeyWindow];
    _giftWindow = nil;
}

如果要回到本页面时再度显示,就在viewWillAppear里调用[self giftButton];即可

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self giftButton];
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/POPLAR_B/article/details/53995476
文章标签: UIWindow button
上一篇Mac重装系统,使用终端命令制作U盘启动
下一篇UIButton+Block分类代替addTarget实现快捷监听按钮点击
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭