ios - 为什么我的 tableView 没有被填充?

标签 ios swift uitableview

我正在尝试用代码中的示例数据填充基本 TableView 。这是我的 View Controller :

import UIKit

class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var postTableView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postcell", for: indexPath)

        cell.textLabel?.text = "title"
        cell.detailTextLabel?.text = "detail"
        return cell
    }
}

这是我的 Storyboard enter image description here

我确定名称 “postcell” 是正确的,并且我已将 tableView 作为数据源和委托(delegate)连接到 ViewController。

当我在 iOS 模拟器中运行代码时,没有显示任何单元格。这是我看到的:

enter image description here

这是我的堆栈 View 的约束 enter image description here

堆栈 View 属性

enter image description here enter image description here

我不想使用UITableViewController

如何让表格单元格出现?

最佳答案

如果“postcell”不是 Storyboard中的原型(prototype)单元格,则需要在 viewDidLoad 中注册它:

    postTableView.register(UITableViewCell.self, forCellReuseIdentifier: "postcell")

如果它是一个 XIB TableView 单元格,您将按如下方式注册它:

    postTableView.register(UINib(nibName: "NibName", bundle: nil), forCellReuseIdentifier: "postcell")

如果您要从 Storyboard 中执行此操作,请将原型(prototype)单元格(或表格 View 单元格)拖到您的表格 View 上,并在重用标识符中将其称为“postcell”,如下所示:

Prototype table view cell

确保您还在 viewDidLoad 中完成了以下操作:

    postTableView.delegate = self
    postTableView.dataSource = self

当然,你还需要:

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

关于ios - 为什么我的 tableView 没有被填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619686/

相关文章:

swift - 第二个 TableView 的 cellForRowAtIndexPath 似乎中断了第一个 TableView

swift - 添加到 TableView 时 Realm 项会出现两次

ios - 如何在 Xcode 7 中启用_BITCODE?

ios - Firebase Chat App - 超时后停止输入指示器

ios - 是否可以在 swift 2 中隐藏 NSURL tel 函数中的号码?

swift - 'fileprivate' 关键字在 Swift 中意味着什么?

objective-c - 默认 UITableview 给出错误或单元格返回 null

ios - swift 4 : Unexpectedly found nil while unwrapping an Optional value

ios - 如何获取 iOS 7 AVSpeechUtterance 文本到语音的不同语言代码?

ios - 如何在 Objective-C 中将 AVAudioPCMBuffer 转换为 NSData?