如何加载 XIB?
我有一个有 2 个屏幕的应用程序(MainViewController 和 AboutViewController)。当用户单击按钮时,我想加载 AboutViewController 屏幕,该屏幕是在另一个 XIB 中定义的。
看起来很简单,但我今天似乎找不到我的谷歌-fu。我怎样才能做到这一点?
I have an app with 2 screens (MainViewController and AboutViewController). Upon the user clicking a button, I'd like to load the AboutViewController screen, which is defined in another XIB.
Seems simple, but I can't seem to find my google-fu today. How do I pull this off?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用
[AboutViewController init]
时,预计会调用某种形式的[super init]
,它是[UIViewController init]
的同义词。发生这种情况时,您的视图控制器将自动查找名为(在您的情况下)AboutViewController.xib
的 nib 文件。如果找到该文件,它会将其内容加载到您的视图控制器中。所以基本上,您需要做的就是初始化视图控制器,并确保它与关联的 nib 文件具有相同的名称。
如果您想将具有不同名称的 nib 文件加载到视图控制器中,您可以显式调用
initWithNibName:bundle:
为您喜欢的 nib 文件的名称。如果标准 init(具有同名 nib 文件)不适合您,您可以检查以下几项内容。
[super init]
UIViewController
子类的 init 方法,When you call
[AboutViewController init]
, it's expected to call some form of[super init]
, which is a synonym for[UIViewController init]
. When this happens, your view controller will automatically look for a nib file called (in your case)AboutViewController.xib
. If it finds that file, it loads it's contents into your view controller for you.So basically, all you need to do is initialize your view controller, and make sure it has the same name as the associated nib file.
If you wanted to load a nib file with a different name into your view controller, you could explicitly call
initWithNibName:bundle:
with the name of whichever nib file you like.If the standard init (with a same-name nib file) isn't working for you, there are a couple things you could check.
UIViewController
subclass's init method does also call[super init]
UIViewController
subclass's init method对于“关于”屏幕,您可能只想显示一个视图,然后将其关闭。因此,您不必使用全新的视图控制器,只需覆盖当前视图即可。
ivar
假设您有一个具有适当属性的
。在视图控制器中执行以下操作:
要删除视图,例如在连接到视图上按钮的操作中,执行以下操作:
With an About screen you probably just want to show a view and then dismiss it. So rather than use a whole new view controller you can just cover the current view.
Assuming you have an ivar
with the appropriate property.
In your view controller do:
To remove the view, say in an action connected to a button on the view, do:
NSBundle loadNibNamed:
NSBundle loadNibNamed: