【问题标题】:Swift TableView in a UIView not displaying dataUIView中的Swift TableView不显示数据
【发布时间】:2015-12-14 04:36:29
【问题描述】:

我想创建一个页面,顶部应该有一个地图,底部应该有 5 行 tableview。所以我创建了 UIViewController 放了我的 Map View 然后放了 TableView。我创建了 myViewController.swift 和 myTableViewCell.swift

但是当我在模拟器上尝试时,tableview 上没有显示数据。只有空单元格。我没有收到错误

这是我的代码。谢谢

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
    }

}

【问题讨论】:

    标签: ios swift uitableview uiview uiviewcontroller


    【解决方案1】:

    设置tableview的dataSource。

    tableview.dataSource = self tableview.delegate = self

    【讨论】:

    • override func viewDidLoad() { super.viewDidLoad() // 添加这个 tableView.delegate = self tableView.dataSource = self }
    【解决方案2】:

    通过storyboard分配UITableView/UICollectionView的delegate和datasource,减少代码如下:

    右键单击您的 UITableView,然后单击代表/数据源的圆形圆圈,然后转到视图控制器。为清楚起见,请参见下图。

    【讨论】:

      【解决方案3】:

      你应该采取两种方式之一:

      tableView.delegate = self
      tableView.dataSource = self
      

      在 viewController 的 viewDidLoad() 中 要么 - 选择 tableView 并通过按控件拖动到 viewController,首先选择数据源,然后再次选择委托。

      【讨论】:

        【解决方案4】:

        试试这个:

        override func viewDidLoad() {
            super.viewDidLoad()
        
            // Add this
            tableView.delegate = self
            tableView.dataSource = self
        }
        

        【讨论】:

        • 我非常努力地解决了这个问题,但解决方案就这么简单吗?:) 非常感谢
        • 这两行到底是做什么的?提前致谢
        • @jorgesaraiva,第一行将委托方法连接到您的委托方法,第二行数据源方法也是如此。您的 TableView 需要这些方法才能开始工作和交互。您需要告诉您的 TableView 哪个 Class 是它的委托和数据源方法。在我们的例子中,控制器类就是我们写“self”的原因
        猜你喜欢
        • 2022-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多