![](/img/trans.png)
[英]when I click button in collection view, i I can't pass value to next view controller
[英]Swift/XCode - Why can't I pass data to the next view controller when a tableViewCell is pressed?
抱歉,如果这已经在其他地方得到了解答,我已经花了两个小时来尝试使用类似的建议尝试其他事情,但是我仍然无法解决!
基本上,我有一个带有自定义单元格的UITableView(用于不同的测验主题),当按下时,应允许应用程序转到下一个VC并传递一个整数,以便下一个VC知道要加载哪个测验。 在我的表格视图VC中,我有以下内容:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
rowPressed = indexPath.row
print ("rowPressed = \(rowPressed) before VC changes")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is GameVC {
let vc = segue.destination as? GameVC
vc?.toPass = rowPressed
print("I ran...")
} else {
print("You suck")
}
在我的GameVC中,我有:
var toPass = Int()
override func viewDidLoad() {
super.viewDidLoad()
print("toPass = \(toPass)")
运行时的控制台输出是这样的:
I ran...
toPass = 0
rowPressed = 3 before VC changes
因此,看起来VC发生了变化,前一个VC可以发送正确的toPass值。 我该如何解决?
提前谢谢了!
根据序列描述:
例如,如果segue源自表视图,那么sender参数将标识用户点击的表视图单元格。
因此,发送者是一个UITableViewCell
,您可以执行以下操作:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let cell = sender as? UITableViewCell else { return }
guard let idx = tableView.indexPath(for: cell) else { return }
guard let vc = segue.destination as? GameVC else { return }
vc.toPass = idx.row
}
您的代码问题是在tableView(didSelectRowAt:)
之前调用了prepare(segue:)
tableView(didSelectRowAt:)
。
如建议的那样,您必须调用performSegue方法:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// not necessary
//rowPressed = indexPath.row
//print ("rowPressed = \(rowPressed) before VC changes")
performSegueWithIdentifier("Your id", sender: indexPath)
//You can set the identifier in the storyboard, by clicking on the segue
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Your id"{
var vc = segue.destinationViewController as! GameVC
vc.toPass = (sender as! IndexPath).row
}
}
因为prepareForSegue
在didSelectRowAt
之前被调用,所以您还可以从情节提要中删除该序列,将ctrl从UITableViewController
的黄色图标顶部拖放到第二个ViewController
,单击该序列,为其指定标识符,所以现在可以调用performSegue
:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.pressed = indexPath.row
self.performSegue(withIdentifier: "segue identifier", sender: nil)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.