我正在尝试从另一个 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/