OGeek|极客世界-中国程序员成长平台

标题: iOS - self.view.frame.size.width 为 0.00000 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 22:48
标题: iOS - self.view.frame.size.width 为 0.00000

我有一个 View Controller (SecondViewController),它有一个名为 setupHomeScreen 的方法,该方法是从另一个 View Controller (FirstViewController) 调用的。此方法在 SecondViewController 初始化后调用。

setupHomeScreen 中,创建了一个 UIView,我希望它具有与主视图相同的边界,这取决于 iPad 是纵向查看还是横向模式。

第一次调用该方法时(在应用启动时), View 完全错误,NSLog 输出显示 self.view.frame.size.width 等于 0.0000

如果我导航到 ThirdViewController,然后返回 SecondViewController,则 View 会正确显示并且 self.view.frame.size.width 的值为 768

我尝试了很多不同的方法来解决这个问题,比如将方法的内容放在 didRotateFromInterfaceOrientationviewDidAppear: 方法中,但似乎没有任何效果。

任何帮助将不胜感激。



Best Answer-推荐答案


When the method is first called (which is on app startup), the view is completely wrong, and an NSLog output shows the self.view.frame.size.width is equal to 0.0000.

这可能是因为 View 尚未加载。 View Controller 在真正需要它们之前不会加载它们的 View ,这通常是在 View 即将第一次显示时。如果您的代码在 View 显示之前尝试查找 View 的宽度,则很有可能该 View 尚未加载。在 Objective-C 中,您可以向 nil 发送消息,结果将是 0 或 nil,具体取决于预期的类型。

If I navigate to ThirdViewController, and then back to SecondViewController, the view is correctly displayed and the self.view.frame.size.width value is 768.

这和上面的解释是一致的;一旦你显示了你的 SecondViewController View 层次结构,这些 View 就会被加载,并且找到你的 View 的宽度是没有问题的。

只需访问 View Controller 的 view 属性就足以使 View 层次结构被加载。如果必须,您可以通过在调用 setupHomeScreen 之前访问 self.view 来解决您的问题。不过,更好的解决方案是在 SecondViewController-viewDidLoad 方法中设置 View 的宽度,这将保持 View Controller 的“延迟加载”行为(并节省内存) 同时仍确保在需要时设置 View 的宽度。

关于iOS - self.view.frame.size.width 为 0.00000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12558916/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4