Good evening. I'm creating my first own app (without following tutorials) that has clickable stuff in AR. I use touchesEnded to get the position of the touch and then I direct a segue if the touch is on an object. But depending on what is touched I want to set the target view controllers' labels, image views etc differently.
Question: Where do I call the prepare for segue method in order to do that or is there a simpler way? When I run the example code (below) I get a crash as a result of an error upon entering the segue saying that testLabel is nil (if I remove the prepare segue bit the segue works fine)
Explanations: 1. 'CaseViewController' is the name of the target view controller and the identifier of my segue 2. In CaseViewController I have connected a UILabel by ctrl + dragging it to the class and it is connected.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! CaseViewController
destinationVC.testLabel.text = "setting of label test"
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touchLocation = touches.first?.location(in: sceneView),
let hitNode = sceneView?.hitTest(touchLocation, options: nil).first?.node,
let nodeName = hitNode.name
else { return }
if nodeName == imageNameArray[0] {
performSegue(withIdentifier: "CaseViewController", sender: self)
//Example: I would ideally want a prepare for segue method here to set the label for this statement only
} else {
print("Found no node connected to \(nodeName)")
return
}
if nodeName == imageNameArray[1] {
performSegue(withIdentifier: "CaseViewController", sender: self)
//And another label setting for this statement etc.
} else {
print("Found no node connected to \(nodeName)")
return
}
print(nodeName)
}
Thanks for reading my question. Kind regards.
The label is nil till teh VC loads
destinationVC.testLabel.text = "setting of label test"
so convert it to
destinationVC.lblText = "setting of label test"
//
class CaseViewController:UIViewController {
var lblText = ""
}
then assign the value to the text inside viewDidLoad
, although touch method is called continuously
Edit:
Use sender to send any value of any type from any if statement
performSegue(withIdentifier: "CaseViewController", sender:"lbl")
then in prepare cast it to it's type
destinationVC.lblText = sender as! String //