開發(fā)中可能經(jīng)常會遇到需要在TableView底部添加工具條的情況,如果直接在TableVIewController的view上添加View作為工具條,會導致滾動tableView時工具條跟隨滾動。
第一種方法:開發(fā)中為了擴展性,控制器還是盡量使用UIViewController,這樣直接在viewController的view上添加tableView,然后將工具條添加在view的最頂層即可。
第二種方法:但是如果之前控價已經(jīng)搭建好了,控制器使用的是UITableViewController,不好再做更改時,我們可以使用UIWindow來完成任務
步驟很簡單:
創(chuàng)建一個UIWindow對象和UIView的toolView對象,將toolView添加到新建的window中,然后調用makeKeyAndVisible顯示window即可
注意:
UIWindow在顯示的時候是不管KeyWindow是誰,都是Level優(yōu)先的,即Level最高的始終顯示在最前面,級別的高低順序從小到大為Normal < StatusBar < Alert
關閉窗口后需要給置為nil
[self.toolWindow resignKeyWindow];
self.toolWindow = nil;-
Xcode8創(chuàng)建并顯示window的方法在viewDidAppear方法中調用,viewDidLoad和viewWillAppear中創(chuàng)建完成后顯示時會報以下錯誤:
報錯(應用程序的窗口沒有根控制器):Application windows are expected to have a root view controller at the end of application launch'如果必須在viewDidLoad方法中創(chuàng)建并顯示window時,使用以下方法調用即可
[self performSelector:@selector(createToolView) withObject:nil afterDelay:0]; // 最后參數(shù)可以設置延時多少秒調用
項目中遇到需要在TableView上使用懸浮按鈕時,也可以這么搞
以下是實現(xiàn)代碼
@interface XYTableViewController ()
@property (nonatomic, strong) UIView *toolView;
@property (nonatomic, strong) UIWindow *toolWindow;
@end
@implementation XYTableViewController
- (void)viewDidAppear:(BOOL)animated {
// 控制器的view顯示完成后執(zhí)行創(chuàng)建并顯示window
[super viewDidAppear:animated];
[self createToolView];
}
- (void)createToolView { // 創(chuàng)建工具條
// 1.創(chuàng)建window
UIWindow *toolWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 44, [UIScreen mainScreen].bounds.size.width, 44)];
// 設置window的等級
toolWindow.windowLevel = UIWindowLevelAlert + 1;
self.toolWindow = toolWindow;
// 2.創(chuàng)建UIView
UIView *toolView = [[UIView alloc] init];
toolView.backgroundColor = [UIColor blueColor];
toolView.frame = toolWindow.bounds;
self.toolView = toolView;
// 3.添加view到窗口
[self.toolWindow addSubview:self.toolView];
// 4.顯示窗口
[self.toolWindow makeKeyAndVisible];
}