我想将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应该在这里工作,但是没有。为什么是这样?
此代码在应用程序委托内部的[window makeKeyAndVisible];
之前执行。所以,难怪为什么keyWindow
还是nil
。
最简单的方法是从应用程序委托中获取窗口:
UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
// Do something with the window now
我注意到在启动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
财产无法通过这种方式到达。
试试这个,首先得到UINavigationController
句柄,然后是topViewController
let navController = window?.rootViewController as! UINavigationController
let yourMainViewController = navController.topViewController as! ItemsViewController
要么
let yourMainViewController = navController.viewControllers.first as! ItemsViewController