斯威夫特:ViewController中的TableView [英] Swift: TableView in ViewController
问题描述
我在MainstoryBoard
中有一个ViewController
.我添加了TableView
I have a ViewController
in the MainstoryBoard
. I added the TableView
to it.
MainStoryBoard:
此外,我在ViewController
类之外有一个数组,我希望该数组内的对象显示在TableView
中.
In addition I have an array outside of the ViewController
class and I want the objects inside the array to be shown in the TableView
.
我不知道该怎么做.我在TableView
和ViewController
之间连接了代理.
I can't figure out how to do it. I connected the delegate between the TableView
and the ViewController
.
推荐答案
您在类声明下方添加了一个新的表视图实例变量.
You add a new table view instance variable below the class declaration.
@IBOutlet weak var tableView: UITableView!
要符合UITableViewDelegate
和UITableViewDataSource
协议,只需在类声明中的UIViewController
之后添加用逗号隔开的
To conform to the UITableViewDelegate
and UITableViewDataSource
protocol just add them separated by commas after UIViewController
in the class declaration
此后,我们需要在ViewController
类中实现tableView(_:numberOfRowsInSection:)
,tableView(_:cellForRowAtIndexPath:)
和tableView(_:didSelectRowAtIndexPath:)
方法,并将它们暂时留空
After that we need to implement the tableView(_:numberOfRowsInSection:)
, tableView(_:cellForRowAtIndexPath:)
and tableView(_:didSelectRowAtIndexPath:)
methods in the ViewController
class and leave them empty for now
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0 // your number of cells 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
}
}
如@ErikP在评论中所述,您还需要 设置
As mentioned by @ErikP in the comments, you also need to set
self.tableView.delegate = self
self.tableView.dataSource = self
在viewDidLoad
方法中.
(或在Storyboard中也很好).
(or in Storyboard works well too).
这篇关于斯威夫特:ViewController中的TableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!