Swift: 变量获取赋值的顺序错误
Swift: variable gets value assigned in the wrong order
我可能在这里遗漏了一些基本的东西,但我有两个 ViewControllers
称为 ListController
(从 VC 开始)和 ExamplesController
以及一个名为 [=15= 的变量] 在 ListController
中声明,然后根据用户点击的行,tableView
didSelectRowAt indexPath
函数在 ListController
中更改其值。当用户点击一个单元格时,将显示 ExamplesController
(通过 IB 中的 segue),但 selectedCell
的值不会改变,直到我返回 ListController
。所以现在执行的顺序是:
selectedCell
gets initialised with a value of 0
user taps on a cell (let's say index 3)
ExamplesController
is presented with title 0
user goes back to ListController
selectedCell
gets assigned the value 3
这是代码的简化版本。
var selectedCell = 0
class ListController: UIViewController, UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedCell = indexPath.row
print("Tapped on \(selectedCell)")
}
}
class ExamplesController: UIViewController{
@IBOutlet weak var chapterTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
chapterTitle.text = "\(chapterTitles[selectedCell])"
}
}
知道我做错了什么吗?
您需要从 vc 本身而非单元格中挂接 segue 并在 didSelectRowAt
内部使用
self.performSegue(withIdentifer:"SegueName",sender:indexPath.row)
func prepare(for segue: UIStoryboardSegue,sender: Any?) {
if segue.identider == "SegueName" {
let des = segue.destination as! ExampleVC
des.selectedCell = sender as! Int
}
}
我可能在这里遗漏了一些基本的东西,但我有两个 ViewControllers
称为 ListController
(从 VC 开始)和 ExamplesController
以及一个名为 [=15= 的变量] 在 ListController
中声明,然后根据用户点击的行,tableView
didSelectRowAt indexPath
函数在 ListController
中更改其值。当用户点击一个单元格时,将显示 ExamplesController
(通过 IB 中的 segue),但 selectedCell
的值不会改变,直到我返回 ListController
。所以现在执行的顺序是:
selectedCell
gets initialised with a value of 0user taps on a cell (let's say index 3)
ExamplesController
is presented with title 0user goes back to
ListController
selectedCell
gets assigned the value 3
这是代码的简化版本。
var selectedCell = 0
class ListController: UIViewController, UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedCell = indexPath.row
print("Tapped on \(selectedCell)")
}
}
class ExamplesController: UIViewController{
@IBOutlet weak var chapterTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
chapterTitle.text = "\(chapterTitles[selectedCell])"
}
}
知道我做错了什么吗?
您需要从 vc 本身而非单元格中挂接 segue 并在 didSelectRowAt
self.performSegue(withIdentifer:"SegueName",sender:indexPath.row)
func prepare(for segue: UIStoryboardSegue,sender: Any?) {
if segue.identider == "SegueName" {
let des = segue.destination as! ExampleVC
des.selectedCell = sender as! Int
}
}