iphone - UIKit 用来确定要加载的正确 nib 名称的模式是什么?

标签 iphone ios cocoa-touch uiviewcontroller uikit

我有一个奇怪的问题: 当您没有明确指定 nibName 时,UIKit 使用什么模式来为 UIViewController 找出正确的 nib 名称?

我为什么要问?

因为我认为(有充分的理由)系统将首先查找与 Controller 类同名的 Nib 。 也就是说,如果我有一个VideoViewController,系统会首先寻找VideoViewController.xib

显然不是这样的。 我有另一个类 VideoView,它是 UIView 的子类。我有一个名为 VideoView.xib 的 nib,它包含 VideoView 的所有 View 层次结构。

当我尝试运行该应用程序时,它立即崩溃并出现 setValue:ForUndefinedKey 异常。 我注意到 key 始终是来自 VideoView.xib 的 key ,不是 来自 VideoViewController.xib。这意味着系统正在尝试为名为 VideoViewController 的 View Controller 加载 VideoView.xib

似乎如果系统将找到名称与 Controller 类名称相似的 nib - 只是没有“Controller”后缀,它将使用该 nib。

我通过将我的类重命名为 VideosViewController(使用“s”)来确认它,并且一切正常。

还有像这样的边缘条件吗? 或者是否有指定确切算法的地方?

调试这个花了我一个小时,以后不想再在同一个问题上浪费时间了...

谢谢!

最佳答案

来自 UIViewController.nibName 属性的文档:

If you use a nib file to store your view controller’s view, it is recommended that you specify that nib file explicitly when initializing your view controller. However, if you do not specify a nib name, and do not override the loadView method in your custom subclass, the view controller searches for a nib file using other means. Specifically, it looks for a nib file with an appropriate name (without the .nib extension) and loads that nib file whenever its view is requested. Specifically, it looks (in order) for a nib file with one of the following names:

  1. If the view controller class name ends with the word “Controller”, as in MyViewController, it looks for a nib file whose name matches the class name without the word “Controller”, as in MyView.nib.
  2. It looks for a nib file whose name matches the name of the view controller class. For example, if the class name is MyViewController, it looks for a MyViewController.nib file.

关于iphone - UIKit 用来确定要加载的正确 nib 名称的模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9081053/

相关文章:

iphone - 哪个按钮调用了该功能?

iphone - 将 NSDate 转换为 mm/dd/yyyy

ios - 如何像 UIAlertView, iOS 那样提供不活动的背景效果?

ios - 我如何将 SFSafariViewController 与这个用户一样的深色主题一起使用?

iphone - Cocoa Touch UI 对象可以序列化、通过网络传输并在客户端上重构吗?

iphone - iOS 7 中的尺寸类别

iphone - iPhone 4,iPhone 5和iPad在用户界面方面有所区别

iphone - 在不是 ICarousel 中的 subview 的标签中显示 iCarousel 的当前索引

ios - 蓝牙 HID 设备和 iOS 文本字段

ios - 上传的二进制文件不会出现在 iOS 中的 iTunes Connect 上