RealityKit & ARKit in SwiftUI — Tap to Place an Item

DevTechie
DevTechie
Published in
5 min readMay 24, 2024

--

RealityKit & ARKit in SwiftUI — Tap to Place an Item

We can interact with objects in the virtual world, so let’s start by detecting the user’s tap to place items at the tapped location.

We will begin by creating a coordinator class. Coordinators in SwiftUI are used to act as delegates for UIKit views and controllers. In UIKit, the delegate objects respond to events when the user presses a button or taps elsewhere in the app.

We will create a final class called ARCoordinator with NSObject conformance.

import ARKit
import Foundation
import RealityKit


final class ARCoordinator: NSObject{

}

This class will need access to the ARView, so we will add a weak property to avoid a retain cycle.

final class ARCoordinator: NSObject {

weak var view: ARView?

This class will have a function that responds to the user’s tap, and this function will act as a selector for TapGestureRecognizer. This function will also provide access to the tap gesture object to get the location of the user's tap.

import ARKit
import Foundation
import RealityKit

final class ARCoordinator: NSObject {

weak var view: ARView?

@objc func didTapItem(tapGesture: UITapGestureRecognizer) {

--

--