在哪里可以指定哪个 UIView 用于 UIViewController 的 view 属性?
我想在运行时设置 UIViewController 的视图属性。我有一个包含两个视图的 .xib 文件,我希望拥有 .xib 文件的 UIViewController 子类决定在运行时使用哪个 UIView。我以为我可以在 loadView 中通过说来做到这一点,
if(some condition)
self.view = thisView;
else
self.view = thatView;
但那不起作用。我该怎么做?
I want to set the view property of a UIViewController at runtime. I have an .xib file with two views, and I want my UIViewController subclass that owns the .xib file to decide which UIView to use at runtime. I thought I could do this in loadView by just saying
if(some condition)
self.view = thisView;
else
self.view = thatView;
but that didn't work. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想动态选择视图,请将其设置在
-[UIViewController loadView]
中。不过需要注意的是:如果视图尚未加载,调用-[UIViewController view]
将会调用-[UIViewController loadView]
,所以如果你这样做:该方法的第二行将调用 -loadView,您将获得无限递归(这将导致堆栈溢出和崩溃)。您需要设置视图,然后在设置后设置
.view
属性,如下所示:因此您可能需要执行如下操作:
附录 1 - 更新展示如何对 XIB 中定义的不同视图使用容器视图
如果您想引用 XIB 中的其他内容,更好的方法是使用 .view 作为其他视图的“容器视图”。在
-viewDidLoad
中进行设置,如下所示:请注意,如果您想稍后交换视图,则应该将
childView
设为属性,而不是局部变量,因此您可以在插入新的childView
时删除旧的childView
。If you want to choose your view dynamically, set it inside
-[UIViewController loadView]
. A word of caution though: calling-[UIViewController view]
will call-[UIViewController loadView]
if the view hasn't been loaded yet, so if you do this:The second line of that method will call
-loadView
, and you'll get infinite recursion (which will lead to a stack overflow, and a crash). You need to setup your view, then set the.view
property when you've set it up, like this:So you'll probably want to do something like this:
Addendum 1 - update to show how to use a container view for different views defined in a XIB
If you want to reference other stuff in your XIB, a better approach is to use your .view as a "container view" for your other views. Set it up in
-viewDidLoad
, like this:Note that if you want to swap your views later on, you should make
childView
a property, instead of a local variable, so you can remove the oldchildView
when inserting a new one.在
-(void)loadView;
方法中是您创建视图的地方,因此您可以在其中有条件地设置它;)Inside
-(void)loadView;
method is where you create your view, so there is where you want to set it conditionally ;)