Pra*_*ani 155 macos uiviewcontroller ios swift
我决定用Swift语言继续我的剩余项目.当我在storyboard viewcontroller中添加自定义类(.swift类,哪个子类到UIViewcontroller)并加载项目时,应用程序突然崩溃并出现以下错误:
致命错误:在课堂上使用未实现的初始化程序'init(coder :)'
这是一个代码:
import UIKit
class TestViewController: UIViewController {
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
Run Code Online (Sandbox Code Playgroud)
请提出建议,
E-R*_*die 203
这是由init?(coder aDecoder: NSCoder)目标上缺少初始化程序引起的UIViewController.该方法是必需的,因为UIViewController从UIStoryboard调用它实例化a .
看看我们如何初始化一个UIViewController从UIStoryboard,请大家看看这里
因为Objective-C自动继承所有必需的UIViewController初始值设定项.
默认情况下,Swift由于安全性而不继承初始化程序.但是如果所有属性都有值(或可选)并且子类没有定义任何指定的初始化器,它将继承超类中的所有初始化器.
手动实现init?(coder aDecoder: NSCoder)目标UIViewController
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
Run Code Online (Sandbox Code Playgroud)
正如Dave Wood在下面的回答中指出的那样,删除init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)目标UIViewController将继承超类中所需的所有初始值设定项
Dav*_*ood 26
除了@ 3r1d之外的另一个选择是从您的类中删除以下init方法:
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
Run Code Online (Sandbox Code Playgroud)
包括init方法,阻止子类继承init(coder aDecoder: NSCoder!)其超类.如果不包括它,你的班级将继承两者.
注:有关更多详细信息,请参阅WWDC 2014 Session 403"Intermediate Swift",大约33:50.
对于与swift存在相同问题的人UICollectionViewCells,请将@ 3r1d建议的代码添加到自定义UICollectionViewCell类而不是View Controller:
init(coder aDecoder: NSCoder!)
{
super.init(coder: aDecoder)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84285 次 |
| 最近记录: |