简体   繁体   English

Swift:ViewController 中的 TableView

[英]Swift: TableView in ViewController

I have a ViewController in the MainstoryBoard .我在MainstoryBoard有一个ViewController I added the TableView to it.我向其中添加了TableView

MainStoryBoard:主线板:

在此处输入图片说明

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 .此外,我在ViewController类之外有一个数组,我希望数组内的对象显示在TableView

I can't figure out how to do it.我不知道该怎么做。 I connected the delegate between the TableView and the ViewController .我在TableViewViewController之间连接了委托。

You add a new table view instance variable below the class declaration.您在类声明下方添加一个新的表视图实例变量。

@IBOutlet weak var tableView: UITableView!

To conform to the UITableViewDelegate and UITableViewDataSource protocol just add them separated by commas after UIViewController in the class declaration为了符合UITableViewDelegateUITableViewDataSource协议,只需在类声明中的UIViewController之后添加以逗号分隔的它们

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之后,我们需要在ViewController类中实现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
    }
}

As mentioned by @ErikP in the comments, you also need to set正如@ErikP 在评论中提到的,您还需要设置

self.tableView.delegate = self

self.tableView.dataSource = self

in the viewDidLoad method.viewDidLoad方法中。

(or in Storyboard works well too). (或者在 Storyboard 中也很好用)。

i might be late and you may have fixed this by now.我可能迟到了,你现在可能已经解决了这个问题。 The error you are getting is due to your variable or constant returning a nil value.您得到的错误是由于您的变量或常量返回 nil 值。 to test this you can assign a value to it (hard code it) and check the full code if it is working and then change it to your array, unfortunately i do stuff programmatically and not very familiar with the storyboard.要对此进行测试,您可以为其分配一个值(对其进行硬编码)并检查完整代码是否有效,然后将其更改为您的数组,不幸的是我以编程方式进行操作并且对故事板不太熟悉。

if you share your code we will be assist you if this is not yet sorted.如果您分享您的代码,如果尚未排序,我们将为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM