ios - 从另一个 swift 文件更改其值后,变量返回 nil 值

标签 ios swift variables null segue

我正在尝试从另一个 Swift 文件更改变量的值,但由于某种原因它不起作用并且返回 nil。

这是我试过的:

class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let si = self.storyboard?instantiateViewController(withIdentifier: "ShowIssueDetail") as! ShowIssueDetail
    si.idSelected = indexPath.row //Here I change the value of the variable
    performSegue(withIdentifier: "ShowIssueDetail", sender: self)
  }
}

ShowIssueDetail.swift:

class ShowIssueDetail: UITableViewController {
  var idSelected: Int! //This is the variable I want to change its value from the another swift file
    override func viewDidLoad() {
      print(idSelected) //Here it prints out nil instead of the selected row
    }
}

我也试过这种方式,但同样的问题:

class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let si = ShowIssueDetail()
    si.idSelected = indexPath.row //Here I change the value of the variable
    performSegue(withIdentifier: "ShowIssueDetail", sender: self)
  }
}

我做错了什么?

提前致谢!

注意:两个swift文件是不同类型的,ShowIssues.swift是UIViewController,ShowIssueDetail是UITableViewController,不知道会不会因此失效。

最佳答案

如果您在 Storyboard 中设置了 segue,则不应从代码中实例化目标 View Controller ,Storyboard 将为您创建 View Controller 。通过初始化另一个实例,您最终会在一个不会呈现给用户的实例上设置值。

您需要覆盖 prepare(for:) 并在那里设置值。

class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "ShowIssueDetail", sender: indexPath.row)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ShowIssueDetail", let destinationVC = segue.destination as? ShowIssueDetail, let selectedId = sender as? Int {
          destinationVC.idSelected = selectedId
        }
    }
}

关于ios - 从另一个 swift 文件更改其值后,变量返回 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53188549/

相关文章:

ios - 指定NSLayoutConstraint的UILayoutPriority好像没有生效

ios - 创建动态 UITextFields 并添加 UIControlEvents.EditingChanged 事件 : who called me?

variables - 直接从csv读取var

java - 在 shell 脚本中使用 JAVA 多行输出作为变量

ios - UITableView 不使用 UISearchBar 滚动

iPhone 相机和照片编辑选项 - 自定义应用程序集成

ios - 使用 CallKit 的 TokBox Audio Session 问题

ios - block 不被调用

javascript - 我如何保存文本框中的输入然后移至下一页? (Javascript/HTML)

ios - 快速发布到 Facebook 不起作用?