5

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)
    }
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
utiq
  • 1,342
  • 2
  • 17
  • 33

2 Answers2

3

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
Rikesh Subedi
  • 1,755
  • 22
  • 21
2

Your code may be as simple as that:

import ARKit

class ViewController: UIViewController, ARSCNViewDelegate {

    lazy var sceneView: ARSCNView = {
        let sceneView = ARSCNView()
        sceneView.delegate = self
        return sceneView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(sceneView)
    
        NSLayoutConstraint.activate([
            sceneView.topAnchor.constraint(equalTo: view.topAnchor),
            sceneView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            sceneView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            sceneView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])
        view.subviews.forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
    }
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220