There may be a need in a project where a button is required at the top of an interface, which may be a post-information feature or a return to the top. So that we can use UIWindow this magical control implementation, very simple.
Full project Source:
Https://github.com/qxuewei/XWSuspendBtn
The final results are as follows:
Implementation logic:
1. Declare the button UIButton property and UIWindow property in the class where the hover button is required
/** window */@property (nonatomic, strong) UIWindow *window;/** 悬浮按钮 */@property (nonatomic, strong) UIButton *button;
2. Create UIWindow and hover button methods
-(void) creatsuspendbtn{//hover button_button = [UIButtonButtonwithtype:uibuttontypecustom]; [_button setimage:[UIImageimagenamed:@"Plus"] Forstate:uicontrolstatenormal];CGFloatScreenWidth = [UIScreen mainscreen]. Bounds. Size. Width;CGFloatScreenHeight = [UIScreen mainscreen]. Bounds. Size. Height; _button. Frame= CGRectMake (0,0, -, -); [_button AddTarget: SelfAction@selector(Suspendbtnclick) forcontrolevents:uicontroleventtouchupinside];///hover button at the top UIWindow_window = [[UIWindowAlloc] Initwithframe:cgrectmake (screenwidth*0.5- +, screenheight- -, -, -)];//Make new window on top_window. Windowlevel= Uiwindowlevelalert +1; _window. BackgroundColor= [UicolorClearcolor]; [_window Addsubview:_button];//Display window[_window makekeyandvisible];}
3. Create a hover button when the view is initialized
- (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];}
Project GitHub Address:
Https://github.com/qxuewei/XWSuspendBtn
ios-hover Button