首页 文章

Swift - 致命错误:在展开Optional值时意外发现nil

提问于
浏览
0

我对使用Swift进行编码并使用Xcode IDE相对较新 . 我正在尝试在故事板中实现新的表视图控制器 . 我已经做了我知道如何做到的一切,但我得到了

致命错误:在解包可选值时意外发现nil

当我点击模拟器中的屏幕时 .

import UIKit

class DrivingTipsTableViewController: UITableViewController
{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ->Int
    {
        return 5
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell =  tableView.dequeueReusableCellWithIdentifier("DrivingLesson") as UITableViewCell
        let label = cell.viewWithTag(69) as UILabel

        if indexPath.row == 0
        {
            label.text = "Setup & ball position"
        }
        else if indexPath.row == 1
        {
            label.text = "Driving lesson 2"
        }
        else if indexPath.row == 2
        {
            label.text = "Driving lesson 3"
        }
        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }

}

它显示了 let label = 线的细分 . 在这个网站上查看一些答案,可能是 dequeueReusableCellWithIdentifier("DrivingLesson") 需要更改,但它与我在IDE中给出我的单元格的标识符相对应,所以我真的不知道我哪里出错了 .

1 回答

  • 1

    首先,您应该在单元格的第一行中使用此方法作为索引路径:

    let cell = tableView.dequeueReusableCellWithIdentifier("DrivingLesson", forIndexPath: indexPath) as UITableViewCell
    

    然后删除 let label = cell.viewWithTag(69) as UILabel 并设置UITableViewCell的textLabel属性:

    cell.textLabel.text = "Some text"
    

相关问题