indexPathForSelectedRow返回nil但未取消选择

时间:2017-03-15 00:28:12

标签: ios swift uitableview segue

在我的prepareForSegue方法中,我试图使用轻触的表格视图单元格来设置目标视图控制器的数据,但应用程序崩溃说明

  

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

我无法理解为什么indexPathForSelectedRow将返回nil。我环顾了类似于我的问题的回答,他们认为问题可能是取消选择所选行,但我不认为这是我的问题。有谁知道它可能是什么?

class ActivityTableViewController: UITableViewController {

    var activities: [Activity] = []

    func generateActivities() {
        let sidecar = Activity(name: "Sidecar Doughnuts", type: "Food", area: "Santa Monica", address: "631 Wilshire Blvd. Santa Monica, California 90401")
        activities.append(sidecar)

        let roseCafe = Activity(name: "Rose Cafe", type: "Food", area: "Venice", address: "220 Rose Ave, Venice, CA 90291")
        activities.append(roseCafe)

        let milkShop = Activity(name: "The Milk Shop", type: "Food", area: "Beverly Hills", address: "7290 BEVERLY BLVD. LOS ANGELES, CA 90036")
        activities.append(milkShop)

        let brentwoodMart = Activity(name: "Brentwood Mart", type: "Food", area: "Brentwood", address: "225 26th St, Santa Monica, CA 90402")
        activities.append(brentwoodMart)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        generateActivities()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return activities.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellIdentifier = "ActivityCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! ActivityCellTableViewCell

        let individualActivity = activities[indexPath.row]

        cell.activityCellTitle.text = individualActivity.name

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier != "showActivityDetails" { return }

        if let dest = segue.destination as? ViewController, let indexPath = tableView.indexPathForSelectedRow {
            dest.activityTypeLabel.text = activities[(indexPath as NSIndexPath).row].type
            dest.areaLabel.text = activities[(indexPath as NSIndexPath).row].area
            dest.addressLabel.text = activities[(indexPath as NSIndexPath).row].address
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您正在安全地展开所选行的indexPath,因此我不认为这就是您遇到崩溃的原因。我猜您忘记为@IBOutlet上尝试设置的3个标签之一添加ViewController,或者如果您没有使用故事板创建它们然后他们可能会在viewDidLoad或其他一个生命周期方法之前初始化。