【问题标题】:indexPathForSelectedRow returning nil but not deselectedindexPathForSelectedRow 返回 nil 但未取消选择
【发布时间】:2017-03-15 00:28:11
【问题描述】:

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

致命错误:在展开 Optional 值时意外发现 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
        }
    }
}

【问题讨论】:

    标签: ios swift uitableview segue


    【解决方案1】:

    您正在安全地解开所选行的 indexPath,所以我认为这不是您遇到崩溃的原因。我猜您忘记为您尝试在ViewController 上设置的这三个标签之一连接@IBOutlet,或者如果您没有使用情节提要创建它们,那么它们可能不会被初始化,直到viewDidLoad 或其他生命周期方法之一。

    【讨论】:

    • OP 正在尝试直接设置标签,而不是将值作为字符串传递并设置在下一个UIViewControllerviewDidLoad
    • 是的,问题是直接设置标签而不是传递值并将其设置在 viewDidLoad 中。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多