从 xib 文件加载 ViewController

2023-09-08移动开发问题
13

本文介绍了从 xib 文件加载 ViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个 MyViewController.swift 和一个 MyViewController.xib 展示 MyViewController 的布局.

I had a MyViewController.swift and a MyViewController.xib presenting the layout of MyViewController.

我尝试了不同的方法来加载这个视图控制器,包括:

I tried different methods to load this view controller including:

//1
let myVC = UINib(nibName: "MyViewController", bundle:
       nil).instantiateWithOwner(nil, options: nil)[0] as? MyViewController

//2
let myVC = NSBundle.mainBundle().loadNibNamed("MyViewController", owner: self, options: nil)[0] as? MyViewController

//3
let myVC = MyViewController(nibName: "MyViewController", bundle: nil)

第三个是唯一成功的初始化,但前两个导致错误:

The third one is the only successful initialisation, but the previous two are causing error:

由于未捕获的异常NSUnknownKeyException"而终止应用程序,

Terminating app due to uncaught exception 'NSUnknownKeyException',

原因:'[setValue:forUndefinedKey:]: this类与键 XXX 的键值编码不兼容.

reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key XXX.

这些加载方法有什么问题?

What's wrong with those loading methods?

推荐答案

Swift 3

let myViewController = MyViewController(nibName: "MyViewController", bundle: nil)
self.present(myViewController, animated: true, completion: nil)

或推入导航控制器

self.navigationController!.pushViewController(MyViewController(nibName: "MyViewController", bundle: nil), animated: true)

这篇关于从 xib 文件加载 ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

Cocos2d - 如何检查不同层中对象之间的交集
Cocos2d - How to check for Intersection between objects in different layers(Cocos2d - 如何检查不同层中对象之间的交集)...
2024-08-12 移动开发问题
8

恢复游戏 cocos2d
Resume game cocos2d(恢复游戏 cocos2d)...
2024-08-12 移动开发问题
6

Cocos2D + 仅禁用 Retina iPad 图形
Cocos2D + Disabling only Retina iPad Graphics(Cocos2D + 仅禁用 Retina iPad 图形)...
2024-08-12 移动开发问题
10

如何将 32 位 PNG 转换为 RGB565?
How to convert 32 bit PNG to RGB565?(如何将 32 位 PNG 转换为 RGB565?)...
2024-08-12 移动开发问题
21

正确的 cocos2d 场景重启?
Proper cocos2d scene restart?(正确的 cocos2d 场景重启?)...
2024-08-12 移动开发问题
7