2015-02-07 72 views
0

我有这样的UITableViewController子类:如何为分组样式创建指定的初始化UITableViewController?

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错误。

很明显,正确的方法是调用指定的初始化程序。不幸的是super.init(nibName: nil, bundle: nil)会创建一个普通样式的tableView。

我可以将let foo: String转换为var foo: String!,并将我的指定初始值设定项变为便捷初始值设定项。像这样:

class MyTableViewController: UITableViewController { 
    var foo: String! 

    convenience init(foo: String, style: UITableViewStyle = .Grouped) { 
     self.init(style: style) 
     self.foo = foo 
    } 
} 

哪个会起作用,但是它打败了let的目的。所以我不想这样做。


我在做什么错?我需要做些什么才能够使用我自己的初始化程序?

回答

0

当然,最好的解决方案是调用指定的初始化程序。但要获得分组样式表视图,您必须使用一个nib文件。

这个笔尖包含一个分组的UITableView。 nib文件的文件所有者是一个UITableViewController。它的视图插座连接到UITableView。非常直截了当。

然后,我们可以使用下面的代码作为我们的init方法:

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) 
    } 
} 

这不是很优雅,但它能够完成任务。