xcode 如何快速使用 prepareForSegue?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36173734/
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 do I use prepareForSegue in swift?
提问by D. Lin
I have a ViewController with tableview called BasicPhrasesVC and I want to pass the data in the selected cell to display it on the next ViewController (called BasicPhrasesVC).
我有一个名为 BasicPhrasesVC 的带有 tableview 的 ViewController,我想传递所选单元格中的数据以将其显示在下一个 ViewController(称为 BasicPhrasesVC)上。
class BasicPhrasesVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
let basicPhrases = ["Hello.","Goodbye.","Yes.","No.","I don't understand.","Please?","Thank you.","I don't know."]
var selectedBasicPhrase = ""
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return basicPhrases.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
cell.textLabel?.text = basicPhrases[indexPath.row]
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
I am unsure of what to put here (I want to pass on the variable "selectedBasicPhrase")
我不确定在这里放什么(我想传递变量“selectedBasicPhrase”)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedBasicPhrase = basicPhrases[indexPath.row]
performSegueWithIdentifier("BasicPhrasesVC2BasicDisplayVC", sender: self)
}
}
Any help is appreciated.
任何帮助表示赞赏。
回答by Chirag D jinjuwadiya
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedBasicPhrase = basicPhrases[indexPath.row]
self.performSegueWithIdentifier("BasicPhrasesVC2BasicDisplayVC", sender: selectedBasicPhrase)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "BasicPhrasesVC2BasicDisplayVC" {
if let nextVC = segue.destinationViewController as? NextViewController {
nextVC.selectedBasicPhrase = sender
}
}
}
回答by Ujjwal
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "<segue name>") {
// pass the data
}
}
回答by Oleg Gordiichuk
Check segue name than take destinationViewController
and send you're data to it.
检查 segue 名称,destinationViewController
然后将您的数据发送给它。
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "BasicPhrasesVC2BasicDisplayVC") {
let viewController:ViewController = segue!.destinationViewController as ViewController
viewController.selectedBasicPhrase = "Test phrase"
}
}