如何为分组样式 UITableViewController 创建指定的 init? [英] How can I create a designated init for a grouped style UITableViewController?
问题描述
我有这个 UITableViewController 子类:
I have this UITableViewController subclass:
class MyTableViewController: UITableViewController {
let foo: String
init(foo: String, style: UITableViewStyle = .Grouped) {
self.foo = foo
super.init(style: style)
}
required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
没什么特别的,不幸的是它没有按预期工作,因为 super.init(style: style)
会调用 MyTableViewController(nibName:bundle:)
.但这并没有在我的课程中实现,因此应用程序将因 fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class
错误而崩溃.
Nothing fancy, unfortunately it does not work as expected because super.init(style: style)
will invoke MyTableViewController(nibName:bundle:)
. But that's not implemented in my class, so the app will crash with a fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class
error.
显然正确的方法是调用指定的构造器.不幸的是 super.init(nibName: nil, bundle: nil)
将创建一个普通样式的 tableView.
Obviously the correct way is to call the designated initializer. Unfortunately super.init(nibName: nil, bundle: nil)
will create a plain style tableView.
我可以把 let foo: String
变成 var foo: String!
并且把我指定的初始化器变成一个方便的初始化器.像这样:
I could turn let foo: String
into var foo: String!
and turn my designated initializer into a convenience initializer. Like this:
class MyTableViewController: UITableViewController {
var foo: String!
convenience init(foo: String, style: UITableViewStyle = .Grouped) {
self.init(style: style)
self.foo = foo
}
}
哪个可行,但它违背了 let
的目的.所以我不想这样做.
Which will work, but it defeats the purpose of let
. So I don't want to do this.
我做错了什么?我必须做什么才能使用我自己的初始化程序?
What am I doing wrong? What do I have to do to be able to use my own initializer?
推荐答案
最好的解决方案当然是调用指定的构造器.但是要获得分组样式的 TableView,您必须使用 nib 文件.
The best solution is of course to call the designated initializer. But to get a Grouped Style TableView you have to use a nib file.
这个笔尖包含一个分组的 UITableView.nib 文件的文件所有者是一个 UITableViewController.它的视图出口连接到 UITableView.很直接.
This nib contains a grouped UITableView. The File Owner of the nib file is a UITableViewController. Its view outlet is connected to the UITableView. Pretty straight forward.
然后我们可以使用以下代码作为我们的 init 方法:
We can then use the following code as our init method:
init(foo: String, style: UITableViewStyle = .Grouped) {
self.foo = foo
if style == .Grouped {
super.init(nibName: "GroupedTableViewController", bundle: nil)
}
else {
super.init(nibName: nil, bundle: nil)
}
}
它不是很优雅,但它完成了工作.
It's not very elegant but it gets the job done.
这篇关于如何为分组样式 UITableViewController 创建指定的 init?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!