UIWindow & UIWindowLevel詳解(轉)
一、UIWindow是一種特殊的UIView,通常在一個程序中只會有一個UIWindow,但可以手動創建多個UIWindow,同時加到程序裡面。UIWindow在程序中主要起到三個作用:
1、作為容器,包含app所要顯示的所有視圖
2、傳遞觸摸消息到程序中view和其他對象
3、與UIViewController協同工作,方便完成設備方向旋轉的支持
二、通常我們可以采取兩種方法將view添加到UIWindow中:
1、addSubview
直接將view通過addSubview方式添加到window中,程序負責維護view的生命周期以及刷新,但是並不會為去理會view對應的ViewController,因此采用這種方法將view添加到window以後,我們還要保持view對應的ViewController的有效性,不能過早釋放。
2、rootViewController
rootViewController時UIWindow的一個遍歷方法,通過設置該屬性為要添加view對應的ViewController,UIWindow將會自動將其view添加到當前window中,同時負責ViewController和view的生命周期的維護,防止其過早釋放
三、WindowLevel
UIWindow在顯示的時候會根據UIWindowLevel進行排序的,即Level高的將排在所有Level比他低的層級的前面。下面我們來看UIWindowLevel的定義:
constUIWindowLevel UIWindowLevelNormal;
constUIWindowLevel UIWindowLevelAlert;
constUIWindowLevel UIWindowLevelStatusBar;
typedef CGFloat UIWindowLevel;
IOS系統中定義了三個window層級,其中每一個層級又可以分好多子層級(從UIWindow的頭文件中可以看到成員變量CGFloat _windowSublevel;),不過系統並沒有把則個屬性開出來。UIWindow的默認級別是UIWindowLevelNormal,我們打印輸出這三個level的值分別如下:
2012-03-27 22:46:08.752 UIViewSample[395:f803] Normal window level: 0.0000002012-03-27 22:46:08.754 UIViewSample[395:f803] Normal window level: 2000.0000002012-03-27 22:46:08.755 UIViewSample[395:f803] Normal window level: 1000.000000
這樣印證了他們級別的高低順序從小到大為Normal < StatusBar < Alert,下面請看小的測試代碼:
TestWindowLevel
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.window.backgroundColor = [UIColor yellowColor];
[self.window makeKeyAndVisible];
UIWindow *normalWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
normalWindow.backgroundColor = [UIColor blueColor];
normalWindow.windowLevel = UIWindowLevelNormal;
[normalWindow makeKeyAndVisible];
CGRect windowRect = CGRectMake(50,
50,
[[UIScreen mainScreen] bounds].size.width - 100,
[[UIScreen mainScreen] bounds].size.height - 100);
UIWindow *alertLevelWindow = [[UIWindow alloc] initWithFrame:windowRect];
alertLevelWindow.windowLevel = UIWindowLevelAlert
alertLevelWindow.backgroundColor = [UIColor redColor];
[alertLevelWindow makeKeyAndVisible];
UIWindow *statusLevelWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, 50, 320, 20)];
statusLevelWindow.windowLevel = UIWindowLevelStatusBar;
statusLevelWindow.backgroundColor = [UIColor blackColor];
[statusLevelWindow makeKeyAndVisible];
NSLog(@"Normal window level: %f", UIWindowLevelNormal);
NSLog(@"Normal window level: %f", UIWindowLevelAlert);
NSLog(@"Normal window level: %f", UIWindowLevelStatusBar);
returnYES;
}