Swift:ViewController中的TableView

时间:2015-07-28 10:23:53

标签: ios iphone swift xcode uitableview

我在ViewController中有一个MainstoryBoard。我添加了TableView 它。

MainStoryBoard:

enter image description here

另外我在ViewController类之外有一个数组,我希望数组中的对象显示在TableView中。

我无法弄明白该怎么做。我在TableViewViewController之间连接了代理。

2 个答案:

答案 0 :(得分:45)

在类声明下面添加一个新的tableview实例变量。

@IBOutlet
var tableView: UITableView!

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

我可能会迟到,你现在可能已经修好了。 您得到的错误是由于您的变量或常量返回零值。为了测试这个,你可以为它分配一个值(硬代码)并检查完整的代码是否正常工作,然后将其更改为你的数组,不幸的是我以编程方式做事并且不太熟悉故事板。

如果你分享你的代码,我们将在你尚未分类的情况下为你提供帮助。