这篇文章,我将分享对UIWindow我所知道的东西。

keyWindow

一个应用能够有许多UIWindow,“The key window”是其中一个,被设计用来接受键盘和其他与点击无关的事件。一个时间段中,如果只有一个Window,那么他就可能是keyWindow。

调用makeKeyAndVisible或者makeKeyWindow,能够使一个UIWindow变成keyWindow。注意,默认情况下,UIWindow是隐藏的。所以调用makeKeyAndVisible,即使一个UIWindow变成了keyWindow,又把它的hidden属性设为NO。

UIWindow is always portrait

在application:didFinishLaunchingWithOptions:中增加以下代码:

 UIView *view = [[UIView alloc] initWithFrame:CGRectMake(, , , )];
view.backgroundColor = [UIColor greenColor];
view.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
[self.window addSubview:view];
view.layer.zPosition = FLT_MAX;

接着,旋转模拟器或者设备,你将会看到绿色视图总在坐标点{0, 0}。

UIWindow’s的坐标系统总是在竖直方向,旋转是通过设置根控制器的位移。所以,自从iOS4开始,应用建议有根控制器。

Keyboard is a window

注意,UIApplication有一个“windows”的实例化方法。

The app’s visible and hidden windows. (read-only)
This property contains the UIWindow objects currently associated with the app. This list does not include windows created and managed by the system, such as the window used to display the status bar.

你能够获取keyboardwindow通过遍历windows array。摘录于SVProgressHUD中得代码。注意,当keyboard显示出来时,window array中包含一种UITextEffectsWindow类型的window。

 - (CGFloat)visibleKeyboardHeight {

     UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if(![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
} for (__strong UIView *possibleKeyboard in [keyboardWindow subviews]) {
if([possibleKeyboard isKindOfClass:NSClassFromString(@"UIPeripheralHostView")] || [possibleKeyboard isKindOfClass:NSClassFromString(@"UIKeyboard")])
return possibleKeyboard.bounds.size.height;
} return ;
}

之前说过,UIWindow的坐标系统总是横屏的,Keyboard也是一个window,所以不管设备是的怎么样的方向,他的frame总是 (0 0; 320 480)。当你旋转设备时,系统发送一个旋转位移消息给keyboard window。

设备旋转到竖屏:

<UITextEffectsWindow: 0x8e3ecc0; frame = ( ;  ); opaque = NO; gestureRecognizers = <NSArray: 0x8e3f240>; layer = <UIWindowLayer: 0x8e3ee40>>

设备旋转到横屏:

<UITextEffectsWindow: 0x8e3ecc0; frame = ( ;  ); transform = [, , -, , -, ]; opaque = NO; gestureRecognizers = <NSArray: 0x8e3f240>; layer = <UIWindowLayer: 0x8e3ee40>>
Notification

如果你注册了UIKeyboardWillShowNotification,你能够确认的是:

 [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
NSLog(@"%@", note);
}];

设备旋转到竖屏:

UIKeyboardFrameEndUserInfoKey = “NSRect: {{0, 264}, {320, 216}}”;

设备旋转到横屏:

UIKeyboardFrameEndUserInfoKey = “NSRect: {{0, 0}, {162, 480}}”;

所以,在你UIKeyboardWillShowNotification接受后,你应该把他转变成你View的坐标系统。代码摘录于Keyboard “WillShow” and “WillHide” vs. Rotation

 - (void) keyboardWillShow:(NSNotification *)aNotification
{
CGRect keyboardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect convertedFrame = [self.view convertRect:keyboardFrame fromView:self.view.window]; ......
/* Do whatever you want now with the new frame.
* The width and height will actually be correct now
*/
......
}

Statusbar is a window

之前说过,windows array不包含the statusbar window,the statusbar window是UIStatusBarWindow类型的,你能够通过以下代码获取。

- (UIWindow *)statusWindow
{
NSString *statusBarString = [NSString stringWithFormat:@"_statusBarWindow"];
return [[UIApplication sharedApplication] valueForKey:statusBarString];
}

就像 the keyboard window, the status bar的大小不会改变,当你旋转屏幕,系统会将旋转消息发送给状态栏。

设备旋转到竖屏:

 <UIStatusBarWindow: 0x8f61e30; frame = ( ;  ); gestureRecognizers = <NSArray: 0x8f62e40>; layer = <UIWindowLayer: 0x8f620d0>>

设备旋转到横屏:

 <UIStatusBarWindow: 0x8f61e30; frame = ( ;  ); transform = [, , -, , , ]; gestureRecognizers = <NSArray: 0x8f62e40>; layer = <UIWindowLayer: 0x8f620d0>>
statusBarFrame

UIApplication有一个属性,叫statusBarFrame,是在竖屏坐标系统下的。

 CGRect rect = [UIApplication sharedApplication].statusBarFrame;
NSLog(@"statusBarFrame %@", NSStringFromCGRect(rect));

设备旋转到竖屏:

statusBarFrame {{0, 0}, {320, 20}}

设备旋转到横屏:

statusBarFrame {{300, 0}, {20, 480}}

如果你仅仅想获取状态栏高度,而不管设备方向,你能通过以下方式获取:

float statusBarHeight = MIN([UIApplication sharedApplication].statusBarFrame.size.height, [UIApplication sharedApplication].statusBarFrame.size.width);
Notification

当设备旋转,系统发送通知UIApplicationWillChangeStatusBarFrameNotification和UIApplicationDidChangeStatusBarFrameNotification。
让我们来看,接受UIApplicationDidChangeStatusBarFrameNotification后处理。

 [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillChangeStatusBarFrameNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
NSLog(@"%@", note);
}]; [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidChangeStatusBarFrameNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
NSLog(@"%@", note);
}];

How to create alert view

有两种方式创建alertView.

Don’t use rootViewController approach

像OLGhostAlertView,SVProgressHUD,WYPopoverController,MTStatusBarOverlay,这样的第三方库,不使用rootViewController。他们创建新window(MTStatusBarOverlay)或者使用存在的UIWindow,他们直接在window上添加子视图。所以他们通过接受UIApplicationDidChangeStatusBarOrientationNotification和UIApplicationWillChangeStatusBarFrameNotification来处理视图方向的。

处理大妈如下,摘录于SVProgressHUD。方法是手动获取屏幕方向并且发送一个 rotation transform 给他的视图。

 - (void)handleOrientationChange:(NSNotification *)note
{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; CGRect orientationFrame = [UIScreen mainScreen].bounds;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame; if(UIInterfaceOrientationIsLandscape(orientation)) {
float temp = orientationFrame.size.width;
orientationFrame.size.width = orientationFrame.size.height;
orientationFrame.size.height = temp; temp = statusBarFrame.size.width;
statusBarFrame.size.width = statusBarFrame.size.height;
statusBarFrame.size.height = temp;
} switch (orientation) {
case UIInterfaceOrientationPortraitUpsideDown:
rotateAngle = M_PI; break;
case UIInterfaceOrientationLandscapeLeft:
rotateAngle = -M_PI/2.0f; break;
case UIInterfaceOrientationLandscapeRight:
rotateAngle = M_PI/2.0f; break;
default: // as UIInterfaceOrientationPortrait
rotateAngle = 0.0; break;
} }
How to add view to existing window

第三方库都有他们的在windows上添加视图的方法。

SVProgressHUD 是在最前面的window上添加视图的。

 if(!self.overlayView.superview){
NSEnumerator *frontToBackWindows = [[[UIApplication sharedApplication]windows]reverseObjectEnumerator]; for (UIWindow *window in frontToBackWindows)
if (window.windowLevel == UIWindowLevelNormal) {
[window addSubview:self.overlayView];
break;
}
}
How the OS creates AlertView

在WWDC 2014 Session 228,“A Look Inside Presentation Controllers”,他们说:

Behind the scenes, the framework creates a window on your app’s behalf, but this predates iOS  window rotation behavior, so this window is technically still in portrait.

We then add the action sheet to that window and mimic the transform hierarchy of the presenting view to get into the right orientation.

Use rootViewController approach

一些第三方库,像FLEX,SIAlertView...他们创建一个新window,并且将根控制器赋予给window。这种方式下,设备方向旋转发送给了rootViewController,他们在根控制器上添加视图。添加视图和控制设备方向的代码都在控制器中。

代码摘抄于FLEXViewExplorerViewController:

 - (NSUInteger)supportedInterfaceOrientations
{
UIViewController *viewControllerToAsk = [self viewControllerForStatusBarAndOrientationProperties];
NSUInteger supportedOrientations = [FLEXUtility infoPlistSupportedInterfaceOrientationsMask];
if (viewControllerToAsk && viewControllerToAsk != self) {
supportedOrientations = [viewControllerToAsk supportedInterfaceOrientations];
} // The UIViewController docs state that this method must not return zero.
// If we weren't able to get a valid value for the supported interface orientations, default to all supported.
if (supportedOrientations == ) {
supportedOrientations = UIInterfaceOrientationMaskAll;
} return supportedOrientations;
} - (BOOL)shouldAutorotate
{
UIViewController *viewControllerToAsk = [self viewControllerForStatusBarAndOrientationProperties];
BOOL shouldAutorotate = YES;
if (viewControllerToAsk && viewControllerToAsk != self) {
shouldAutorotate = [viewControllerToAsk shouldAutorotate];
}
return shouldAutorotate;
} - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[...]
} - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[...]
}

因为FLEX创建了新Window,Window必须询问app原始的Window才能获取旋转消息。注意infoPlistSupportedInterfaceOrientationsMask和viewControllerForStatusBarAndOrientationProperties两个属性。你能够从中学到很多。

UIWindow is a UIView

因为UIWindow是UIView的子类,你能够想UIView一样对UIWindow做很多事情。

例如,FLEX重写了pointInside:withEvent: to,用来拦截它的toolbar上的点击。

 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
BOOL pointInside = NO;
if ([self.eventDelegate shouldHandleTouchAtPoint:point]) {
pointInside = [super pointInside:point withEvent:event];
}
return pointInside;
}

UIWindow in iOS 8

在iOS8,苹果引入了Size Classes,并且“旋转是一种动画式的视图边界变化”。并且UIWindow能够获取屏幕旋转通知。

在WWDC 2014 Session 216,《Building Adaptive Apps with UIKit》

Trait Environments are a new protocol that are able to return their current Trait Collection, and these include Screens, Windows, View Controllers, and also Views.

All of these are able to return their current Trait Collection to you to use to determine how your interface should be laid out.

UIWindow in iOS的更多相关文章

  1. [iOS基础控件 - 6.10.7] UIWindow

    A.UIWindow概念 1.继承UIView,是一种特殊的UIView 2.通常一个APP只有一个UIWindow 3.iOS程序启动后,创建的第一个视图就是UIWindow 4.没有UIWindo ...

  2. iOS开发之UIWindow

    1.概述 UIWindow是一种特殊的UIView,通常在一个app中只会有一个UIWindow. iOS程序启动完毕后,创建的第一个视图控件就是UIWindow,接着创建控制器的view,最后将控制 ...

  3. iOS.UI.UIWindow

    UIWindow 1. UIWindow 2. UIWindow的使用场景 2.1 额外添加的Window需要手动进行旋转 最近有遇到一个UIWindow的使用场景:在ApplicationDeleg ...

  4. AJ学IOS(22)UI之UIApplicationDelegate和UIWindow

    AJ分享,必须精品 UIApplicationDelegate 每次新建完项目,都有个带有“AppDelegate”字眼的类,它就是UIApplication的代理 NYAppDelegate默认已经 ...

  5. 你真的了解UIWindow吗?

    一:首先查看一下关于UIWindow的定义 NS_CLASS_AVAILABLE_IOS(2_0) @interface UIWindow : UIView //window的屏幕,默认是 [UISc ...

  6. 关于UIWindow(转)

    (原文出自:http://www.cnblogs.com/wendingding/p/3770052.html,特别感谢) 一:[[UIScreen mainScreen] bounds] 和[UIS ...

  7. iOS开发之App启动原理

    iOS程序的启动过程 程序启动的完整过程大致步骤如下: 1.main函数 2.UIApplicationMain * 创建UIApplication对象 * 创建UIApplication的deleg ...

  8. iOS UIKit:view

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css); @import url(/ ...

  9. iOS Multiview Applications

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css); @import url(/ ...

随机推荐

  1. Oracle之事务

    一,oracle的事务: 是指对数据操作的一系列动作的统称.即:事务的任务便是使数据库从一种状态变换成为另一种状态,这不同于文件系统,它是数据库所特用的. 事务有四大特性(ACID): 1,原子性(a ...

  2. 理解JavaScript中作用域链的关系

    javascript里的关系又多又乱.作用域链是一种单向的链式关系,还算简单清晰:this机制的调用关系,稍微有些复杂:而关于原型,则是prototype.proto和constructor的三角关系 ...

  3. 【回顾整理】暴走的SQL语句练习!!!

    设计一个学生成绩数据库,该库包含学生,老师,课程和成绩等信息并完成后面的练习.学生:学号(SNO).姓名(SNAME).性别(SSEX).生日(SBIRTHDAY ).所属班级(SCLASS )课程: ...

  4. js获得url的参数

    网上找的一段代码,非常好用,现在难以找到原作者,但是非常感谢!/**   * 获取当前URL参数值  * @param name  参数名称  * @return  参数值   */ function ...

  5. RDLC 聚合函数按条件求和,显示"错误号"

    =Sum(IIf(Fields!AValue.Value >0,Val(Fields!AValue.Value),)) 一直显示错误号 修改为 =Sum(IIf(Fields!AValue.Va ...

  6. Android(通用机能)

    数据存储 本地数据存在都是私有化的. 共享方法1是构造数据源组件.方法2将数据放入扩展存储设备. Mashup 服务组件默认没有运行在独立进程或线程中,因此费时操作一般需要起线程.可配置指定新进程. ...

  7. Xcode7国际化(根据系统语言切换App显示的语言) - 元宵节快乐!

    老规矩, 上gif 下面是配置的大概流程: 这个是要显示中文的.strings文件的内容和格式 这个是要显示英文的.strings文件的内容和格式 下面是应用名部分: 然后下面是代码部分: impor ...

  8. Dijkstra算法 最短路径 (部分)

    void Dijkstra(int n, int v, int *dist, int *prev, int c[maxnum][maxnum]) {     bool s[maxnum];       ...

  9. C#邮件发送(最坑爹的邮箱-QQ邮箱)---转发(SmallFlyElephant)

    C#邮件发送(最坑爹的邮箱-QQ邮箱) 最近工作挺清闲的,有空的时候陪妹子出去玩玩,自己看看小说,看看电影,日子过的挺欢乐的,这个星期幡然悔悟,代码才是我的最爱,做点小东西,就写个邮件发送程序.说的邮 ...

  10. flash里面调用js

    在flash里面直接调用js 用这个:ExternalInterface.call("test");  test是函数名