Swift:通过在方法中的if语句中准备segues来设置UI元素



晚上好。我正在创建我自己的第一个应用程序(没有以下教程(,它在AR中有可点击的东西。我使用touchesEnded来获取触摸的位置,然后如果触摸在对象上,我会引导一个segue。但根据触摸的内容,我想以不同的方式设置目标视图控制器的标签、图像视图等。

问:为了做到这一点,我在哪里调用prepare for segue方法,或者有更简单的方法吗?当我运行示例代码(如下(时,由于输入segue时出现错误,称testLabel为nil,我会崩溃(如果我删除prepare segue位,则segue工作正常(

解释:1CaseViewController是目标视图控制器的名称,也是我的segue 2的标识符。在CaseViewController中,我通过ctrl+拖动UILabel到类中来连接它,它就被连接了。

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)

}

谢谢你阅读我的问题。致以亲切的问候。

在VC加载之前,标签为零

destinationVC.testLabel.text = "setting of label test"

所以将其转换为

destinationVC.lblText = "setting of label test"

//

class CaseViewController:UIViewController {
var lblText = ""
}

然后将值分配给viewDidLoad内的文本,尽管触摸方法被称为连续

编辑:

使用发送方从任意if语句发送任何类型的任何值

performSegue(withIdentifier: "CaseViewController", sender:"lbl")

然后在准备中将其铸造为类型

destinationVC.lblText = sender as! String //

最新更新