ios 在 Swift 中使用 performSegueWithIdentifier 执行转场时如何传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35398309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass parameters when performing a segue using performSegueWithIdentifier in Swift
提问by venkat kotu
I am calling a segue programatically, Can any one please help me how can pass parameters ?
我正在以编程方式调用 segue,有人可以帮助我如何传递参数吗?
@IBAction func update(sender: AnyObject) {
self.performSegueWithIdentifier("showUpdate", sender: nil)
}
回答by Ryan Huebert
Swift 4:
斯威夫特 4:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ExampleSegueIdentifier" {
if let destinationVC = segue.destination as? ExampleSegueVC {
destinationVC.exampleStringProperty = "Example"
}
}
}
Swift 3:
斯威夫特 3:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ExampleSegueIdentifier" {
if let destinationVC = segue.destinationViewController as? ExampleSegueVC {
destinationVC.exampleStringProperty = "Example"
}
}
}
回答by Ahmed Onawale
The performSegueWithIdentifier method takes two arguments, 1. the segue identifier, 2. the parameter you are passing which is of type AnyObject?
performSegueWithIdentifier 方法有两个参数,1. segue 标识符,2. 您传递的参数是AnyObject类型的参数吗?
@IBAction func update(sender: AnyObject) {
self.performSegueWithIdentifier("showUpdate", sender: sender)
}
Then in the prepareForSegue method, you check the segue identifier and cast the sender parameter to the type you passed in earlier.
然后在 prepareForSegue 方法中,您检查 segue 标识符并将 sender 参数转换为您之前传入的类型。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showUpdate" {
guard let object = sender as? ObjectToUpdateType else { return }
let dvc = segue.destinationViewController as! DestinationViewController
dvc.objectToInject = object
}
}
回答by D. Greg
Prepare for segue can pass data along.
准备转场可以传递数据。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "showUpdate") {
if let vc: DestinationVC = segue.destinationViewController as? DestinationVC {
vc.variable = variableToPass
}
}
}