我在ViewController
中有一个MainstoryBoard
。我添加了TableView
它。
MainStoryBoard:
另外我在ViewController
类之外有一个数组,我希望数组中的对象显示在TableView
中。
我无法弄明白该怎么做。我在TableView
和ViewController
之间连接了代理。
答案 0 :(得分:45)
在类声明下面添加一个新的tableview实例变量。
@IBOutlet
var tableView: UITableView!
要符合UITableViewDelegate
和UITableViewDataSource
协议,只需在类声明中UIViewController
之后用逗号分隔它们
之后,我们需要在tableView(_:numberOfRowsInSection:)
课程中实施tableView(_:cellForRowAtIndexPath:)
,tableView(_:didSelectRowAtIndexPath:)
和ViewController
方法,暂时将其留空
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0 // your number of cell here
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// your cell coding
return UITableViewCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// cell selected code here
}
}
答案 1 :(得分:1)
我可能会迟到,你现在可能已经修好了。 您得到的错误是由于您的变量或常量返回零值。为了测试这个,你可以为它分配一个值(硬代码)并检查完整的代码是否正常工作,然后将其更改为你的数组,不幸的是我以编程方式做事并且不太熟悉故事板。
如果你分享你的代码,我们将在你尚未分类的情况下为你提供帮助。