UITableViewCell没有显示

Jul*_*nez 2 xcode uitableview ios swift

我正在创建一个简单的表但没有故事板,只是编码,目前我可以创建表但是当我添加它崩溃的单元格时,这些是我的变量:

var optionsTableView:UITableView!
var options = ["Option1", "Option2"]
Run Code Online (Sandbox Code Playgroud)

当我点击按钮时,表格出现,功能是:

@IBAction func Options(sender: AnyObject) {
    if optionsTableView != nil {
        optionsTableView.removeFromSuperview()
        self.optionsTableView = nil
        return
    }

    self.optionsTableView = UITableView()
    self.optionsTableView.backgroundColor = UIColor(white: 0, alpha: 0.95)
    self.optionsTableView.delegate = self
    self.optionsTableView.dataSource = self
    self.optionsTableView.translatesAutoresizingMaskIntoConstraints = false

    var constraints = [NSLayoutConstraint]()
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 100.0))
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Trailing, relatedBy: .Equal, toItem: sender, attribute: .Trailing, multiplier: 1.0, constant: 0))
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Top, relatedBy: .Equal, toItem: sender, attribute: .Bottom, multiplier: 1.0, constant: 5.0))

    self.view.addSubview(optionsTableView)
    self.view.addConstraints(constraints)

    optionsTableView.addConstraints([NSLayoutConstraint(item: optionsTableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 220.0)])
}
Run Code Online (Sandbox Code Playgroud)

表的功能:

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.options.count
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 44.0
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切顺利,但使用cellForRowAtIndexPath应用程序崩溃:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")!
    if tableView == optionsTableView {
        cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
        cell.backgroundView = nil
        cell.backgroundColor = UIColor.clearColor()
        cell.textLabel?.textColor = UIColor.whiteColor()
        cell.textLabel?.text = self.options[indexPath.row]
        return cell
    }
    return cell
}
Run Code Online (Sandbox Code Playgroud)

特别是在这一行应用程序崩溃:

var cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")!
Run Code Online (Sandbox Code Playgroud)

并且控制台说:"致命错误:在打开一个Optional值时意外地发现nil",您认为发生了什么?

Wye*_*tro 5

该行崩溃是因为它没有找到具有该重用标识符的单元格.

你必须注册它:

self.tableView.registerClass(Cell.self as AnyClass, forCellReuseIdentifier: "cell")
Run Code Online (Sandbox Code Playgroud)

这样当你强制打开它时它不会崩溃.