简体   繁体   English

如何加载XIB?

[英]How to load an XIB?

I have an app with 2 screens (MainViewController and AboutViewController). 我有一个带2个屏幕的应用程序(MainViewController和AboutViewController)。 Upon the user clicking a button, I'd like to load the AboutViewController screen, which is defined in another XIB. 用户单击按钮后,我想加载AboutViewController屏幕,该屏幕在另一个XIB中定义。

Seems simple, but I can't seem to find my google-fu today. 看起来很简单,但我今天似乎无法找到我的谷歌。 How do I pull this off? 我怎么把它关掉?

When you call [AboutViewController init] , it's expected to call some form of [super init] , which is a synonym for [UIViewController init] . 当你调用[AboutViewController init] ,它应该调用某种形式的[super init] ,它是[UIViewController init]的同义词。 When this happens, your view controller will automatically look for a nib file called (in your case) AboutViewController.xib . 发生这种情况时,视图控制器将自动查找名为(在您的情况下) AboutViewController.xib的nib文件。 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. 基本上,您需要做的就是初始化视图控制器,并确保它与关联的nib文件具有相同的名称。

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. 如果要将具有不同名称的nib文件加载到视图控制器中,可以显式调用initWithNibName:bundle: :,使用您喜欢的任何nib文件的名称。

If the standard init (with a same-name nib file) isn't working for you, there are a couple things you could check. 如果标准init(具有相同名称的nib文件)不适合您,您可以检查几件事。

  • the spelling of the class name is the same as the spelling (and case) of the nib file 类名的拼写与nib文件的拼写(和大小写)相同
  • the nib file is included in the project, and not just sitting in the same directory nib文件包含在项目中,而不只是位于同一目录中
  • your UIViewController subclass's init method does also call [super init] 你的UIViewController子类的init方法也调用[super init]
  • you are calling your UIViewController subclass's init method 你正在调用你的UIViewController子类的init方法
  • you are indeed making your view controller's view visible 你确实让你的视图控制器的视图可见

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 假设你有一个伊娃

UIView *aboutUsView;

with the appropriate property. 有适当的财产。

In your view controller do: 在您的视图控制器中执行:

[[NSBundle mainBundle] loadNibNamed:@"AboutUsView" owner:self options:nil]; // Retains top level items
[self.view addSubview:aboutUsView];  // Retains the view
[aboutUsView release];

To remove the view, say in an action connected to a button on the view, do: 要删除视图,例如在连接到视图上按钮的操作中,请执行以下操作:

[aboutUsView removeFromSuperview], aboutUsView = nil;  // Releases the view

NSBundle loadNibNamed:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM