ios - 在 Swift 中持续更新 UILabel

标签 ios swift arkit

我正在创建一个应用程序,它将在检测到图像时不断更新平面节点的坐标。但是,我想知道我将如何做到这一点。我的代码如下:

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/

相关文章:

ios - 在 UICollectionView 中显示一行中不同数量的单元格

python - PyAPNS无法在生产环境中将推送消息传递到iOS设备

iOS ARKit 指向 anchor 的指针

ios - 调整 tabbarcontroller 中所有 viewcontroller 框架的大小

Swift Playground 错误 - FBSOpenApplicationErrorDomain 代码 =4

swift - 如何跳过 for-in 循环的迭代(Swift 3)

ios - 获取 PHAsset 的本地文件路径

ios - ARKit - 扩展 "hitTest"的范围

animation - 如何 “crop” SCNAnimationPlayer 到特定的开始和结束时间,iOS 11

ios - 获取包含按下​​的 UIButton 的自定义 UITableViewCell