我正在创建一个应用程序,它将在检测到图像时不断更新平面节点的坐标。但是,我想知道我将如何做到这一点。我的代码如下:
extension ViewController: ARSCNViewDelegate {
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
DispatchQueue.main.async {
guard let imageAnchor = anchor as? ARImageAnchor,
var imageName = imageAnchor.referenceImage.name else { return }
let planeNode = self.getPlaneNode(withReferenceImage: imageAnchor.referenceImage)
planeNode.opacity = 1.0
planeNode.eulerAngles.x = -.pi / 2
planeNode.runAction(self.fadeAction)
node.addChildNode(planeNode)
let nodeCam = self.sceneView.session.currentFrame!.camera
let cameraTransform = nodeCam.transform
planeNode.position.x = cameraTransform.columns.3.x + 1
planeNode.position.y = cameraTransform.columns.3.y + 1
if imageName == "sample" {
self.imageOne.text = "\"\(imageName)\""
self.instructions.text = "IMAGE DETECTED: \"\(imageName)\""
self.coordinateView.isHidden = false
self.updateOne.isHidden = false
self.coordinateX.text = "X: " + String(planeNode.position.x)
self.coordinateY.text = "Y: " + String(planeNode.position.y)
}
如何才能让坐标X和坐标Y对应的标签在平面节点移动时不断变化更新呢?我尝试过重复循环,其中:
repeat {
self.coordinateX.text = "X: " + String(planeNode.position.x)
self.coordinateY.text = "Y: " + String(planeNode.position.y)
} while imageName == "sample"
但这只会导致代码在检测到图像时卡住。有什么建议么?
最佳答案
这里有两个选项;您可以设置一个 DispatchSource 来注册计划的事件并建立一个处理程序。该处理程序可以是将点设置到标签中的函数。示例:
func startUpdating() {
timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
timer?.schedule(deadline: DispatchTime.now(),
repeating: DispatchTimeInterval.milliseconds(16),
leeway: .milliseconds(5))
timer?.setEventHandler(qos: .userInitiated, flags: [], handler: self.update)
timer?.resume()
}
func update() {
coordinateX.title = String(planeNode.position.x)
coordinateY.title = String(planeNode.position.y)
}
如果您认为数据会在短时间内更新/更改很多,那么这非常有用。
如果您认为不会发生这种情况,那么我将使用“didSet”来监视变量并在“didSet”函数中设置该函数。
关于ios - 在 Swift 中持续更新 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51865444/