Search code examples
iosswiftaugmented-realityscenekitarkit

Add ARSCNView programmatically


How can I add a ARSCNView programmatically? How can I set width, height and constraints?.

class ViewController: UIViewController {

    var sceneView: ARSCNView!
    let configuration = ARWorldTrackingConfiguration()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.sceneView.debugOptions = [ARSCNDebugOptions.showFeaturePoints, ARSCNDebugOptions.showWorldOrigin]
        self.sceneView.session.run(configuration)
    }
}

Solution

  • If you are just asking about how to add ARSCNView, then my answer would be:

    //instantiate scene view in viewDidLoad
    sceneView = ARSCNView()
    
    //add it to parents subview
    self.view.addSubview(sceneView)
    
    //add autolayout contstraints
    sceneView.translatesAutoresizingMaskIntoConstraints = false
    sceneView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
    sceneView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    sceneView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
    sceneView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
    
    //load your scene