UIWindow的bounds/frame为空

3

我正在创建一个不使用nib文件的iOS应用程序,并希望在应用程序委托中初始化窗口,如下所示:

CGRect screenBounds = [[UIScreen mainScreen] bounds];
self.window = [[[UIWindow alloc] initWithFrame:screenBounds] autorelease];
self.window.backgroundColor = [UIColor greenColor];

NSLog(@"%@", self.window.bounds);

窗口弹出,我可以看到我定义的绿色。当我调试self.window时,我可以看到刚刚定义的框架的边界,但是当我想要访问bounds属性时,它返回null。frame也是一样。有什么区别?
当我想初始化视图时,它不起作用,因为未定义框架/边界以初始化该视图:
// create root view
RootView* rootView = [[[RootView alloc] initWithFrame:self.window.bounds] autorelease];

我做错了什么吗?
2个回答

6

是的,这样行不通

NSLog(@"%@", self.window.bounds);

窗口边界不是一个对象,所以无法使用 %@ 显示它 :)
尝试先将 CGRect 转换为 NSString * :
NSLog(@"%@", NSStringFromCGRect(self.window.bounds));

这将为您提供更多的调试信息,以帮助您解决问题 :)

NB %@ 仅仅是调用对象的description方法并显示其结果。


0

你应该使用格式说明符来格式化NSLog框架:

NSLog(@"x=%.1f, y=%.1f, width=%.1f, height=%.1f", 
      self.window.bounds.origin.x, 
      self.window.bounds.origin.y, 
      self.window.bounds.size.width, 
      self.window.bounds.size.height);

3
有一个辅助方法可以帮你完成这个任务 - NSStringFromCGRect :) 详见文档:http://developer.apple.com/library/ios/#documentation/uikit/reference/UIKitFunctionReference/Reference/reference.html#//apple_ref/doc/uid/TP40006894-CH3-SW19 - deanWombourne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接