自定义视图单元格的属性设置为nil(UITableView)

时间:2018-02-09 14:55:05

标签: ios swift xcode uitableview tableview

cellForRowAt中的表视图单元格总是将所有属性设置为nil

import UIKit

class TodoTableViewCell: UITableViewCell {
    @IBOutlet weak var label: UILabel!
}

class TodosViewController: UITableViewController {

    @IBOutlet var TodosTableView: UITableView!
    var projects = [Project]()
    var todos = [Todo]()

    override func viewDidLoad() {
        super.viewDidLoad()
        TodosTableView.delegate = self
        self.tableView.register(TodoTableViewCell.self, forCellReuseIdentifier: "TodoTableViewCell1")
        // data init
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "TodoTableViewCell1"
        var todo = projects[indexPath.section].todos[indexPath.row]
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TodoTableViewCell else {
            fatalError("The dequeued cell is not an instance of MealTableViewCell.")
        }

        cell.label?.text = todo.text // cell.label is always nil
        return cell
    }
}

outlet class

identifier identifier

似乎是完全相同的问题 Custom table view cell: IBOutlet label is nil

我试图做的事情: - 重启Xcode - 重新创建插座 - 清洁项目 - 从头开始​​重新创建视图单元格https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/custom-cells/

请帮助,iOS开发已经让我疯了。

3 个答案:

答案 0 :(得分:2)

如果您在Interface Builder中使用原型单元,则不需要在tableview中注册该类。尝试从viewDidLoad删除注册功能。顺便提一下,你也可以在IB中设置dataSource和delegate - 更简洁的代码。

答案 1 :(得分:1)

您正在使用UITableView实例方法:

func register(AnyClass?, forCellReuseIdentifier: String)

这仅适用于未使用Interface Builder

设置自定义UITableViewCell子类的情况

如果您使用xib创建了子类。你应该使用:

func register(UINib?, forCellReuseIdentifier: String)

像:

let nib = UINib(nibName: "\(TodoTableViewCell.self)", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "TodoTableViewCell1")

如果您在故事板中使用原型单元格,则根本不需要注册单元格。

答案 2 :(得分:0)

我认为单元格的标识符应位于属性检查器列的标识符中,而不是标识检查器 并在身份检查器的模块中添加您的项目