UIApplication sharedApplication - keyWindow是nil?

问题描述 投票:28回答:4

我想将CGPoint从我的UIView转换为UIWindow坐标,并意识到UIApplication keyWindow总是为零;为什么是这样?

我尝试过UIView的convertPoint:toView:方法。

请在Xcode模板(View应用程序)中查看我在视图控制器中尝试的示例代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *test =  [[UIView alloc] initWithFrame:CGRectMake(40,40,250,250)];
    [test setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:test];

    CGPoint p = CGPointMake(100, 100);
    CGPoint np;

    np = [test convertPoint:p toView:[[UIApplication sharedApplication] keyWindow]];
    NSLog(@"p:%@ np:%@", NSStringFromCGPoint(p), NSStringFromCGPoint(np));

    AppDelegate *appDel =  (AppDelegate *)[UIApplication sharedApplication].delegate;

    np = [test convertPoint:p toView:[appDel window]];
    NSLog(@"p:%@ np:%@", NSStringFromCGPoint(p), NSStringFromCGPoint(np));

    np = [test convertPoint:p toView:nil];
    NSLog(@"p:%@ np:%@", NSStringFromCGPoint(p), NSStringFromCGPoint(np));

    [test release];

    if(![[UIApplication sharedApplication] keyWindow])
        NSLog(@"window was nil");
}

我得到:

p:{100, 100} np:{100, 100}
p:{100, 100} np:{140, 160}
p:{100, 100} np:{100, 100}
window was nil

我可以转换它,但只有当我通过app委托访问窗口时。而不是UIApplication。根据文档,keyWindow应该在这里工作,但是没有。为什么是这样?

iphone objective-c uiapplicationdelegate uiapplication
4个回答
40
投票

此代码在应用程序委托内部的[window makeKeyAndVisible];之前执行。所以,难怪为什么keyWindow还是nil


34
投票

最简单的方法是从应用程序委托中获取窗口:

UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
// Do something with the window now

12
投票

我注意到在启动Guided Access之后,[UIApplication sharedApplication]上的keyWindow属性似乎为零。

在设置>常规>引导访问中启用引导访问模式后第一次启动引导访问模式时,仅在iOS7上发生这种情况,因此实际显示起始GAM视图而不是旁路。

由于这个Apple API似乎有问题,我解决了使用以下代码来检索我正在寻找的窗口。

NSArray *windows = [[UIApplication sharedApplication] windows];
if ([windows count]) {
    return windows[0];
}
return nil;

代替

[[UIApplication sharedApplication] keyWindow];

也许你也可以尝试使用

[[[UIApplication sharedApplication] delegate] window];

正如iWasRobbed所指出的那样,但它并不适合我,因为rootViewController财产无法通过这种方式到达。


0
投票

试试这个,首先得到UINavigationController句柄,然后是topViewController

let navController = window?.rootViewController as! UINavigationController
let yourMainViewController = navController.topViewController as! ItemsViewController

要么

let yourMainViewController = navController.viewControllers.first as! ItemsViewController
© www.soinside.com 2019 - 2024. All rights reserved.