在UIView中使用Swift TableView未显示数据

7

我希望创建一个页面,页面顶部应该有地图,底部是一个5行的表格视图。所以我创建了一个UIViewController,放上了我的MapView,然后放置TableView。我创建了myViewController.swift和myTableViewCell.swift。

但是当我在模拟器上尝试时,表格视图没有显示数据,只有空白单元格。我没有收到任何错误信息。

这是我的代码。谢谢。

import UIKit
import MapKit

class myViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var mapView: MKMapView!

    var labels = ["some arrays"]

    var images = ["some image names in an array"]

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return labels.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("mySegue", forIndexPath: indexPath) as! myTableViewCell

        cell.myCellLabel.text = labels[indexPath.row]
        cell.myCellImage.image = UIImage(named: images[indexPath.row])

        return cell
    }

}
4个回答

15

试试这个:

override func viewDidLoad() {
    super.viewDidLoad()

    // Add this
    tableView.delegate = self
    tableView.dataSource = self
}

我一直在努力解决这个问题,但解决方案竟然如此简单?:) 非常感谢。 - ggnoredo
这两行代码实际上是做什么的?提前感谢。 - jorge saraiva
1
@jorgesaraiva,第一行将委托方法连接到您的委托方法,第二行同样适用于数据源方法。您的TableView需要这些方法才能开始工作和交互。您需要告诉TableView它的委托和数据源方法在哪个类中。在我们的情况下,它是控制器类,因此我们写“self”。 - Masterfego

7
你应该选择以下两种方式中的一种:
tableView.delegate = self
tableView.dataSource = self

在您的视图控制器的viewDidLoad()方法中 或者 - 选择tableView并按住control键拖动到viewController,先选择dataSource再进行选择delegate。

1

通过Storyboard分配UITableView/ UICollectionView的代理和数据源,可以减少代码量,步骤如下:

右键单击您的UITableView,然后单击Delegate/ Datasource的圆形图标,并移动到视图控制器。为了清晰起见,请参见下面的图像。

Click here to view screenshot


0

设置tableview的数据源。

tableview.dataSource = self tableview.delegate = self


1
重写函数 viewDidLoad() { super.viewDidLoad()// 添加以下内容 tableView.delegate = self tableView.dataSource = self} - Dinesh Saini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接