简体   繁体   中英

Swift - Fatal error: unexpectedly found nil while unwrapping an Optional values

I am relatively new to coding with Swift and working with the Xcode IDE. I am trying to implement a new Table View Controller into the storyboard. I have done everything I know how to do this, but I get the

Fatal error: unexpectedly found nil while unwrapping an Optional values

when I click through to the screen in the simulator.

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)
    }

}

It shows the breakdown at the let label = line. Looking through some answers on this site, it may be the dequeueReusableCellWithIdentifier("DrivingLesson") that needs changing, but it corresponds with the identifier I gave my cell in the IDE, so I really have no idea where I am going wrong.

First, you should use this method in your first line of your cell for index path:

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

Then delete let label = cell.viewWithTag(69) as UILabel and just set UITableViewCell's textLabel property:

cell.textLabel.text = "Some text"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM