代码之家  ›  专栏  ›  技术社区  ›  Alexander Kozachenko

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

  •  1
  • Alexander Kozachenko  · 技术社区  · 8 年前

    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 回复  |  直到 8 年前
        1
  •  4
  •   Ash    8 年前

    如果在Interface Builder中使用原型单元,则无需在tableview中注册该类。尝试从中删除注册功能 viewDidLoad . 顺便提一下,您还可以在IB中设置数据源和委托,这在代码方面要整洁得多。

        2
  •  2
  •   beyowulf    8 年前

    您正在使用 UITableView 实例方法:

    func register(AnyClass?, forCellReuseIdentifier: String)
    

    仅当您的自定义 UITableViewCell 未使用Interface Builder设置子类

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

    func register(UINib?, forCellReuseIdentifier: String)
    

    例如:

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

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

        3
  •  0
  •   Vasilis D.    8 年前

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

    推荐文章