干净的方式强制视图提前加载子视图 [英] Clean way to force view to load subviews early
问题描述
最近我写了一些代码,我试图引用 UIViewController上的插座
我刚用 [storyboard instantiateViewControllerWithIdentifier]实例化
并在呈现 ViewController
之前修改插座指向的子视图。它没有用,因为 ViewController
的视图还没有加载它的子视图,包括我的出口引用的那个,所以属性只给了我一个空指针。
Recently I wrote some code where I tried to refer to an outlet on a UIViewController
I'd just instantiated with [storyboard instantiateViewControllerWithIdentifier]
and modify the subview that the outlet pointed to before presenting the ViewController
. It didn't work because the ViewController
's view hadn't loaded its subviews yet, including the one that my outlet referred to, so the property just gave me a null pointer.
在调试器中追踪我的问题的原因(经过一番努力)之后,我用Google搜索并通过这一个,我可以使视图加载其子视图而不显示通过调用 myViewController.view
getter。在那之后,我可以毫无问题地访问我的插座。
After (with some struggle) tracking down the cause of my issue in the debugger, I Googled around and learned, through answers like this one, that I can cause the view to load its subviews without being displayed by calling the myViewController.view
getter. After that, I can access my outlet without any problems.
这是一个明显的黑客,但是,Xcode - 非常正确 - 不喜欢它,并愤怒地抗议此警告:
It's a clear hack, though, and Xcode - quite rightly - doesn't like it, and angrily protests with this warning:
未使用属性访问结果 - 不应将getter用于副作用
Property access result unused - getters should not be used for side effects
是否有非hacky替代方法来执行此操作,但不涉及滥用 .view
getter?或者,是否存在这种情况的规范/惯用模式,包括动态添加处理程序以便在加载子视图时立即调用?
Is there a non-hacky alternative way to do this that doesn't involved abusing the .view
getter? Alternatively, are there canonical/idiomatic patterns for this scenario involving something like dynamically adding a handler to be called as soon as the subviews are loaded?
或者是标准解决方案用 [myViewController view]
替换 myViewController.view
来关闭Xcode的警告,然后和黑客一起生活?
Or is the standard solution just to replace myViewController.view
with [myViewController view]
to shut up Xcode's warning, and then live with the hack?
推荐答案
在iOS 9或更高版本上,可以使用:
On iOS 9 or newer, one can use:
viewController.loadViewIfNeeded()
文档: https://developer.apple.com/reference/uikit/uiviewcontroller/1621446-loadviewifneeded
这篇关于干净的方式强制视图提前加载子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!