我在 MainstoryBoard
中有一个 ViewController
。我添加了 TableView
主 Storyboard:
此外,我在 ViewController
类之外有一个数组,我希望数组中的对象显示在 TableView
中。
我不知道该怎么做。我在 TableView
和 ViewController
之间连接了委托(delegate)。
最佳答案
您在类声明下方添加一个新的 TableView 实例变量。
@IBOutlet weak var tableView: UITableView!
要符合 UITableViewDelegate
和 UITableViewDataSource
协议(protocol),只需在类声明中的 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 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 在评论中提到的,您还需要 设置
self.tableView.delegate = self
self.tableView.dataSource = self
在 viewDidLoad
方法中。
(或者在 Storyboard 中效果也很好)。
关于ios - Swift:ViewController 中的 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31673607/