我想要将CGPoint从我的UIView转换为UIWindow坐标,并且已经意识到UIApplication keyWindow总是为零;为什么会这样?
我已经尝试过UIView中的convertPoint:toView:方法。
请在Xcode (视图应用程序)的模板中查看我在视图控制器中尝试过的示例代码:
- (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我可以转换它,但仅当我通过应用程序委托访问窗口时。而不是UIApplication。根据文档,keyWindow应该可以在这里工作,但它是空的。为什么会这样呢?
发布于 2010-07-30 22:22:03
此代码是在应用程序委托中的[window makeKeyAndVisible];之前执行的。所以,难怪为什么keyWindow还会是nil。
发布于 2013-03-26 04:05:42
最简单的方法是从应用程序代理中获取窗口:
UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
// Do something with the window now发布于 2014-01-10 19:19:03
我注意到在启动引导式访问后,UIApplication sharedApplication上的keyWindow属性似乎为空。
只有当我在设置>常规>引导访问中启用引导访问模式后第一次启动引导访问模式时,这种情况才会发生在iOS7上,所以启动GAM视图实际上是显示的,而不是跳过。
由于这个Apple API似乎有buggy,所以我使用以下代码解决了这个问题,以检索我正在寻找的窗口。
NSArray *windows = [[UIApplication sharedApplication] windows];
if ([windows count]) {
return windows[0];
}
return nil;而不是
[[UIApplication sharedApplication] keyWindow];也许您也可以尝试使用
[[[UIApplication sharedApplication] delegate] window];正如iWasRobbed指出的,但它对我不起作用,因为rootViewController属性不能以这种方式访问。
https://stackoverflow.com/questions/3359501
复制相似问题