我对快速语言不熟悉并且知道这个问题是重复的。我发现了几个类似的问题和答案,但我无法弄清楚问题。
我想从ScanViewController传递detectString变量的值到ResultViewController。
ScanViewcontroller如下:
import UIkit
class ScanViewController: UIViewController {
var detectionString : String!
override func viewDidLoad() {
super.viewDidLoad()
detectionString = “SomeDetectedString”
}
override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) {
if (segue.identifier == "MySegue") {
var svc = segue.destinationViewController as ResultViewController;
svc.detectedString = detectionString
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
ResultViewController如下:
import UIkit
class ResultViewController: UIViewController {
var detectedString: String!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor=UIColor.whiteColor()
println(detectedString)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
println(detectedString)没有给我任何结果。问题是如何从ScanViewController获取变量?
答案 0 :(得分:1)
你的segue.identifier == "MySegue"
是如何不以它的方式进行比较的。
使用以下功能替换您的代码,您就完成了。
override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) {
let segueName: String = segue.identifier!;
if (segueName == "MySegue") {
var svc = segue.destinationViewController as DetailVC;
svc.detectedString = detectionString
}
}
答案 1 :(得分:1)
您有三种选择:
prepareForSegue
方法获取目标ViewController并设置属性答案 2 :(得分:1)
这可能听起来很奇怪,但你的代码没有任何问题,但它不能正常工作。我使用了相同的代码而忽略了segue。然后我将ScanViewController
嵌入到故事板中的导航控制器中。我还打电话给self.performSegueWithIdentifier("MySegue", sender: self)
中的ScanViewController viewDidLoad
来启动segue。然后一切都像魅力一样。你的prepareForSegue很好。 Yuvrajsinh的建议很好,但没有必要(我在将DetailVC更改为ResultViewController后尝试了)。没有导航控制器没有任何作用。 segue.identifier
是一个字符串,它将在一个直接的Swift字符串比较中工作。
以下是ScanViewController的代码:
import UIkit
class ScanViewController: UIViewController {
var detectionString : String!
override func viewDidLoad() {
super.viewDidLoad()
detectionString = "SomeDetectedString"
println(detectionString)
self.performSegueWithIdentifier("MySegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) {
if (segue.identifier == "MySegue" || segue.identifier == "SegueFromButton") {
println("prepareForSegue")
var svc = segue.destinationViewController as ResultViewController;
svc.detectedString = detectionString
println("svc.detectedString: \(svc.detectedString)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
和ResultViewController:
import UIkit
class ResultViewController: UIViewController {
var detectedString: String!
override func viewDidLoad() {
println("Result Load View")
super.viewDidLoad()
self.view.backgroundColor=UIColor.whiteColor()
println("detectedString in Result: \(detectedString)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}