斯威夫特:ViewController中的TableView [英] Swift: TableView in ViewController

查看:60
本文介绍了斯威夫特:ViewController中的TableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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.

我不知道该怎么做.我在TableViewViewController之间连接了代理.

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!

要符合UITableViewDelegateUITableViewDataSource协议,只需在类声明中的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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆