utiq
utiq

Reputation: 1381

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)
    }
}

Upvotes: 6

Views: 3336

Answers (2)

Andy Jazz
Andy Jazz

Reputation: 58553

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
        }
    }
}

Upvotes: 3

Rikesh Subedi
Rikesh Subedi

Reputation: 1855

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

Upvotes: 5

Related Questions