ARKit:如何在情节提要中向 ARView 添加按钮?

ARKit: How to add button to ARView in storyboard?

我是 ARKit 的新手(也是 swift 的新手),但我正在尝试创建一个基本的 AR 应用程序。我正在关注 this tutorial in which a simple scene is created essentially doing everything in reality composer apart from the addition of a simple start scene button which is added to the ARView in the storyboard - you can see that specific moment in the tutorial here。但是,当我尝试执行相同操作时,button 元素完全替换了 ARView,而不是像本教程中那样将其添加为 ARView 的子元素。

您可以在下面看到正在发生的事情。这是我添加按钮之前的故事板。

然后我搜索一个按钮元素,拖到 ARView 上,此时它将替换它,而不是添加为子元素。结果见下方。

我的 xcode 版本是 11.2。

非常感谢任何建议,如果需要更多信息,请询问。谢谢。

您必须将 ARView 和 Button 都嵌套在 UIView 下。首先,添加 UIView 作为 ViewController 的直接子代。然后,在您之前创建的 UIView 下添加一个 ARView。然后,您还可以在同一个 UIView 下添加一个 UIButton

编辑:在查看您问题中链接的教程视频后,"ARView" 教程作为 ViewController 的子项不是实际的 ARView,而是 UIView 重命名为 "ARView",以澄清。

手动(在 main.storyboard 中)

  • 删除当前ARView
  • 添加 UIView
  • 添加新的 ARView
  • 激活布局约束
  • 添加按钮

以编程方式

向 RealityKit ARView 添加按钮的最简单方法是以编程方式添加它们。使用这种方法,您不需要删除当前的ARView。如果您想以编程方式激活 NSLayoutConstraints,请阅读

这是一个代码。

import RealityKit
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    
    override func viewDidLoad() {
        super.viewDidLoad()           
        let boxAnchor = try! Experience.loadBox()
        arView.scene.anchors.append(boxAnchor)
        
        let rect1 = CGRect(x: 50, y: 50, width: 100, height: 50)
        let rect2 = CGRect(x: 120, y: 50, width: 100, height: 50)
        
        // PLAY BUTTON
        let playButton = UIButton(frame: rect1)
        playButton.setTitle("Play", for: .normal)
        playButton.addTarget(self, action: #selector(play), for: .touchUpInside)
        
        // STOP BUTTON
        let stopButton = UIButton(frame: rect2)
        stopButton.setTitle("Stop", for: .normal)
        stopButton.addTarget(self, action: #selector(stop), for: .touchUpInside)

        self.view.addSubview(playButton)
        self.view.addSubview(stopButton)
        
        self.loadAudio()
    }       
    @objc func play(sender: UIButton!) {
        self.audioController?.play()
    }
    @objc func stop(sender: UIButton!) {
        self.audioController?.pause()
    }
}

乔伊说得对。出于某种原因,Apple 的 AR 模板不包含 UIView,您以 Nick 描述的内容结束。这是一步一步的过程,因此您可以将 Interface Builder 与 RealityKit 结合使用:

  • 创建新项目
  • Select 增强现实应用
  • 输入产品名称。 Select RealityKit 用于内容技术,Storyboard 用于用户界面。
  • Select Main.storyboard.
  • 按“+”并在 ARVIew
  • 上添加一个 UIVIew
  • 现在再次按“+”拖动 RealityKit AR 视图
  • 将新的 ARView 连接到视图控制器中的 arView 出口。
  • 现在您也可以添加 UI 个元素,而无需替换 AR 视图。