標籤:
在項目中可能會有這種需求,即在一個介面最頂層需要一個按鈕,這個按鈕可能是發布資訊功能,也可能是回到頂部.這樣我們可以使用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
iOS-懸浮按鈕