【问题标题】:Table View items are not showing表视图项目未显示
【发布时间】:2021-01-26 20:49:54
【问题描述】:

我是 iOS 开发新手。

我正在尝试使用 UITableView 在我的应用中显示项目列表,但项目未显示:

我的视图控制器:

class HistoryView: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    
    let cellReuseIdentifier = "cell"
    
    @IBOutlet weak var noDataLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier: "historyCell")
        
        tableView.delegate = self
        tableView.dataSource = self
        self.noDataLabel.isHidden=true
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "historyCell") as! HistoryTableViewCell

        cell.nickname?.text = "name"
        
        return cell
    }

    
}

我的表格视图单元格:

class HistoryTableViewCell: UITableViewCell {
    
    @IBOutlet weak var nickname: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

对发生的事情有什么建议吗?

【问题讨论】:

  • numberOfRowsInSection 被调用了吗? (检查print 或断点。)
  • 检查你的tableview没有隐藏
  • 您使用的是原型单元格吗?如果是,则您不得注册该单元。
  • 表格视图未隐藏
  • 是 numberOfRowsInSection 调用了 10 次

标签: ios swift uitableview tableview


【解决方案1】:

条件 1:
如果您使用的是原型单元格,请删除该行

tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier:"historyCell")

并在情节提要中给出单元格标识符

条件 2: 如果您使用的是 xib 文件,则像下面这样注册单元格:-

tableView.register(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: "historyCell")

【讨论】:

    【解决方案2】:

    你需要像这样注册单元格

    tb.register(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: "historyCell")
    

    我看到@IBOutlet weak var nickname: UILabel!

    class HistoryTableViewCell


    对于表格单元格,

    dequeueReusableCellregister,应该成对调用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 2015-12-24
      • 2023-03-14
      相关资源
      最近更新 更多