无法将值传递给另一个 viewController? [英] Cant pass value to another viewController?

查看:31
本文介绍了无法将值传递给另一个 viewController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 tableview 单元格中有一些文本,您将点击它,您将传递单元格的名称,并且您将被推送到另一个视图.

I have some text in tableview cells which you will tap on it you will pass the name of the cell and also you will be pushed to another view.

       override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath as IndexPath, animated: true)

    let row = indexPath.row
    valueToPass = sections[row]
    print(valueToPass)
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if (segue.identifier == "fromWelcomeToSectionPage") {
        // initialize new view controller and cast it as your view controller
         let vc:sectionPage = segue.destination as! sectionPage
        vc.passedValue = valueToPass

    }
}

我也在另一个控制器中创建了代码来检查

also I created code in another controller to check

    if passedValue == "Základy" {
        print("it works")
    }

这就是我试图通过它的方式.变量 valueToPass 是全局变量.Idk 但是当我在 didSelectRowAtIndexPath 中打印它时,它很好,但在准备时它为零.
点击单元格后,我在展开可选值时意外发现 nil

This is how I trying to pass it. Variable valueToPass is global variable. Idk but when I'm printing it in didSelectRowAtIndexPath it's okey but in prepare it's nil.
After tapping on cell I've got unexpectedly found nil while unwrapping an Optional value

这就是我在另一个视图中创建变量的方式

That's how I created variable in another view

var passedValue = String()

推荐答案

你的 prepareForSegue 方法在 didSelectRowAt 方法之前被调用,所以你不能依赖任何逻辑您可以在 didSelectRow 中帮助传递数据.

Your prepareForSegue method is called before the didSelectRowAt method, so you can't rely on any logic you do in didSelectRow to help pass the data.

您可以在 prepareForSegue 中获取所选行并在那里使用它来获取数据并将其传递:

You can get the selected row in prepareForSegue and use it there to get the data and pass it along:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if (segue.identifier == "fromWelcomeToSectionPage") {
         // initialize new view controller and cast it as your view controller
         let vc = segue.destination as! sectionPage
         let selectedRow = tableView.indexPathForSelectedRow!.row
         vc.passedValue = sections[selectedRow]
    }
}

这篇关于无法将值传递给另一个 viewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆