首页 > 解决方案 > 表视图,视图控制器,表单元格零错误

问题描述

我已经创建了一个 ViewController,我的 Storyboard 链接到它。我以前做过,而且效果很好。这一次,当我对表格视图和表格视图单元格使用几乎完全相同的代码时,它在运行时返回 nil 错误。我不确定究竟是什么原因。

//
//  IngView1.swift
//  Fake
//
//  Created by Ian Dong on 11/16/20.
//

import UIKit

class IngView1: UIViewController, UITableViewDataSource {

    @IBOutlet weak var display: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        display.dataSource = self
    }
    
    var data = ["Oil     5","Beef     3","Chicken     5","Potato     4","Cheese     3","Fish     3","Cabage     4"]
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "IngReUse")! // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

        let text = data[indexPath.row]
        cell.textLabel?.text = text
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
}

标签: swiftxcodeuitableviewuiviewcontroller

解决方案


你确定你正确设置了原型单元的标识符吗?您可以在情节提要中执行此操作。

或者如果你不使用原型单元,你可以在代码中注册它

display.register(UITableViewCell.self, forCellReuseIdentifier: "IngReUse")

推荐阅读