Sample CodeiOS, iPadOSReviewed 2026-11-01View on Apple Developer

Creating screen annotations for objects in an AR experience

At a glance

Item Summary
Purpose Annotate an AR experience with virtual sticky notes that you display onscreen over real and virtual objects.
App architecture One storyboard-driven UIKit app target. A single ViewController holds a RealityKit ARView, the list of StickyNoteEntity anchors, and the overlay views. Each entity carries a ScreenSpaceComponent that owns a UIKit StickyNoteView; every scene update projects the entity’s 3D position to a 2D screen point and moves the view there.
Main patterns One controller split into extension files by concern; a HasScreenSpaceView protocol whose extension supplies screen-positioning behavior to entities; UIKit and ARKit delegate callbacks.
Project style ScreenSpace-Sample/ViewController/ grouped by role: Components/, Entities/, Views/, Gestures/, Delegates/, Utilities/.
Execution model No Swift concurrency. A RealityKit SceneEvents.Update subscription drives projection; DispatchQueue.main.async and asyncAfter schedule label and alert updates; UIViewPropertyAnimator animates views.
State/event model Direct mutation of component flags (isDragging, isEditing, shouldAnimate, projection), a scene-event subscription, a keyboard notification observer, and target-action gestures.
Key frameworks/packages RealityKit, ARKit, UIKit, Combine (for the Cancellable type). The project declares no Swift package.

Project structure

ScreenSpace-Sample.xcodeproj/        one app target, iOS 15.0, iPhone and iPad
ScreenSpace-Sample/
├── AppDelegate.swift                ARKit support check, scene configuration
├── SceneDelegate.swift              empty UIWindowSceneDelegate (storyboard scene)
└── ViewController/
    ├── ViewController.swift         ARView, sticky-note list, scene-update projection
    ├── Components/ScreenSpaceComponent.swift   HasScreenSpaceView, ScreenSpaceComponent, Projection
    ├── Entities/StickyNoteEntity.swift         Entity + HasAnchoring + HasScreenSpaceView
    ├── Views/                       StickyNoteView, MessageLabel, GradientView, ViewController+OverlayUI
    ├── Gestures/ViewController+Gestures.swift  tap to create, pan to move or delete
    ├── Delegates/                   ViewController+UITextViewDelegate, +ARCoachingOverlayDelegate
    └── Utilities/                   keyboard, UIView, and SIMD helpers

Structure observations

  • ViewController is one class split across six files. The extensions group gestures, overlay layout, text editing, coaching, and keyboard handling (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:11, ScreenSpace-Sample/ViewController/Views/ViewController+OverlayUI.swift:11, ScreenSpace-Sample/ViewController/Delegates/ViewController+UITextViewDelegate.swift:11, ScreenSpace-Sample/ViewController/Utilities/Keyboard+Helpers.swift:12).
  • The Main storyboard creates ViewController, its ARView, and the MessageLabel. The Info.plist scene configuration loads that storyboard for SceneDelegate (ScreenSpace-Sample/Info.plist:42).
  • The overlay views (shadeView, trashZone, the reset button, and the coaching overlay) are built in code, not in the storyboard (ScreenSpace-Sample/ViewController/Views/ViewController+OverlayUI.swift:15).
  • The target builds for iPhone and iPad with an iOS 15.0 deployment target (ScreenSpace-Sample.xcodeproj/project.pbxproj:448, ScreenSpace-Sample.xcodeproj/project.pbxproj:457).

Overall architecture

Reference code

ScreenSpace-Sample/ViewController/ViewController.swift:64 — projecting each note to the screen on every scene update

    func updateScene(on event: SceneEvents.Update) {
        let notesToUpdate = stickyNotes.compactMap { !$0.isEditing && !$0.isDragging ? $0 : nil }
        for note in notesToUpdate {
            // Gets the 2D screen point of the 3D world point.
            guard let projectedPoint = arView.project(note.position) else { return }
            
            // Calculates whether the note can be currently visible by the camera.
            let cameraForward = arView.cameraTransform.matrix.columns.2.xyz
            let cameraToWorldPointDirection = normalize(note.transform.translation - arView.cameraTransform.translation)
            let dotProduct = dot(cameraForward, cameraToWorldPointDirection)
            let isVisible = dotProduct < 0

            // Updates the screen position of the note based on its visibility
            note.projection = Projection(projectedPoint: projectedPoint, isVisible: isVisible)
            note.updateScreenPosition()
        }
    }

Interpretation

Observed: the 3D side and the 2D side are joined by one per-frame loop. The entity is the source of truth for world position; the view is the source of truth for on-screen position only while a note is being dragged or edited, which is why updateScene skips those notes. When a drag ends, attemptRepositioning raycasts from the view’s center and writes the result back to the entity’s transform (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:172).

Inference: storing the UIKit view inside a component keeps “which view belongs to which entity” on the entity itself, so the per-frame loop needs only the entity list.

Ownership and state

Ownership evidence

ScreenSpace-Sample/ViewController/Entities/StickyNoteEntity.swift:12 — the entity creates and owns its view through the component

class StickyNoteEntity: Entity, HasAnchoring, HasScreenSpaceView {

    var screenSpaceComponent = ScreenSpaceComponent()
    
    /// Initializes a new StickyNoteEntity and assigns the specified transform.
    /// Also automatically initializes an associated StickyNoteView with the specified frame.
    init(frame: CGRect, worldTransform: simd_float4x4) {
        super.init()
        self.transform.matrix = worldTransform
        screenSpaceComponent.view = StickyNoteView(frame: frame, note: self)
    }
    // ...
}
Owner Object or state Relationship Mutation authority
ViewController stickyNotes Appends each new entity after adding it to the scene (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:77) ViewController; removed in deleteStickyNote(_:) (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:164)
ARView.scene Each StickyNoteEntity as an anchor arView.scene.addAnchor(note) (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:67) Removed with note.removeFromParent()
StickyNoteEntity ScreenSpaceComponent (value type) and, through it, the StickyNoteView Created in the initializer Flags written by ViewController extensions through HasScreenSpaceView accessors
StickyNoteView stickyNote back-reference weak var (ScreenSpace-Sample/ViewController/Views/StickyNoteView.swift:15) Set once in init(frame:note:)
arView (UIKit hierarchy) Each StickyNoteView as a subview Inserted below trashZone (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:71) ViewController
ViewController subscription Stores the scene-update Cancellable (ScreenSpace-Sample/ViewController/ViewController.swift:29, ScreenSpace-Sample/ViewController/ViewController.swift:36) Never cancelled in source; released with the controller
ViewController selectedStickyView, lastKeyboardHeight Editing state written by text and keyboard callbacks (ScreenSpace-Sample/ViewController/ViewController.swift:23, ScreenSpace-Sample/ViewController/Utilities/Keyboard+Helpers.swift:22) ViewController

Observed: the entity-to-view link is strong (component property) and the view-to-entity link is weak, so there is no retain cycle between the pair. ScreenSpaceComponent conforms to RealityKit Component, but the entity stores it in its own property rather than in entity.components, and no System processes it.

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Per-frame callback arView.scene.subscribe(to: SceneEvents.Update.self) with [unowned self] Calls updateScene(on:), which moves UIKit views directly. The delivery queue is not established in source. ScreenSpace-Sample/ViewController/ViewController.swift:36
Subscription lifetime var subscription: Cancellable! Retained for the controller’s lifetime; no explicit cancel() ScreenSpace-Sample/ViewController/ViewController.swift:29
Main-queue alert DispatchQueue.main.async in session(_:didFailWithError:) Builds and presents the restart alert on the main queue ScreenSpace-Sample/ViewController/ViewController.swift:101
Main-queue label updates DispatchQueue.main.async and asyncAfter in MessageLabel.displayMessage Shows text, then hides it after duration unless a newer message changed tag ScreenSpace-Sample/ViewController/Views/MessageLabel.swift:30, ScreenSpace-Sample/ViewController/Views/MessageLabel.swift:39
Notification observer NotificationCenter.default.addObserver for keyboardWillChangeFrameNotification Added in every viewWillAppear; no matching removal in source ScreenSpace-Sample/ViewController/ViewController.swift:52
Animation UIViewPropertyAnimator Animates a note to its projected point and clears shouldAnimate on completion ScreenSpace-Sample/ViewController/Components/ScreenSpaceComponent.swift:66, ScreenSpace-Sample/ViewController/Components/ScreenSpaceComponent.swift:70

Reference code

ScreenSpace-Sample/ViewController/Views/MessageLabel.swift:20 — a tag check cancels stale hide requests

    func displayMessage(_ text: String, duration: TimeInterval = 3.0) {
        guard !ignoreMessages else { return }
        // ...
        DispatchQueue.main.async {
            self.isHidden = false
            self.text = text
        }
        
        // Use tag to tell if the label has been updated.
        let tag = self.tag + 1
        self.tag = tag
        
        DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
            // Do not hide if showMessage is called again before this block kicks in.
            if self.tag == tag {
                self.isHidden = true
            }
        }
    }

Observed: the sample has no shared state that it protects with a lock, actor, or private queue. stickyNotes and the component flags are read in the scene-update callback and written in gesture and text callbacks. Not established by source: that the scene-update callback runs on the main thread. Inference: the code relies on that, because updateScene sets UIKit frames without a hop.

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
Scene events RealityKit SceneEvents.Update subscription The only driver of 3D-to-2D projection ScreenSpace-Sample/ViewController/ViewController.swift:36
Component state HasScreenSpaceView computed properties forwarding to screenSpaceComponent Gesture, text, and coaching code read and write isDragging, isEditing, shouldAnimate, projection ScreenSpace-Sample/ViewController/Components/ScreenSpaceComponent.swift:21
Delegate callbacks UITextViewDelegate, ARSessionDelegate, ARCoachingOverlayViewDelegate ViewController sets itself as each text view’s delegate and as the session and coaching delegate ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:80, ScreenSpace-Sample/ViewController/ViewController.swift:43, ScreenSpace-Sample/ViewController/Views/ViewController+OverlayUI.swift:97
Notification UIResponder.keyboardWillChangeFrameNotification Stores the keyboard height and resizes the selected note ScreenSpace-Sample/ViewController/Utilities/Keyboard+Helpers.swift:18
Framework import UIKit, RealityKit, Combine, ARKit Combine supplies the Cancellable type only; no publisher operators appear ScreenSpace-Sample/ViewController/ViewController.swift:8
Package declaration None The project file declares no Swift package ScreenSpace-Sample.xcodeproj/project.pbxproj:448

Class and protocol design

Reference code

ScreenSpace-Sample/ViewController/Components/ScreenSpaceComponent.swift:11 — an Entity-constrained protocol with default behavior

protocol HasScreenSpaceView: Entity {
    var screenSpaceComponent: ScreenSpaceComponent { get set }
}
extension HasScreenSpaceView {
    // ...
    // Updates the screen space position of an entity's screen space view to the current projection.
    func updateScreenPosition() {
        guard let projection = projection else { return }
        let projectedPoint = projection.projectedPoint
        // Hides the sticky note if it can not visible from the current point of view
        isEnabled = projection.isVisible
        view?.isHidden = !isEnabled

        if shouldAnimate {
            animateTo(projectedPoint)
        } else {
            setPositionCenter(projectedPoint)
        }
    }
    
}
Type Responsibility Depends on
ViewController ARView host, note list, per-frame projection, reset, every callback ARView, StickyNoteEntity, overlay views
HasScreenSpaceView (protocol + extension) Forwarding accessors plus centering, animating, and showing or hiding the view ScreenSpaceComponent, Entity.isEnabled
ScreenSpaceComponent (struct) Holds the view and the drag, edit, animate, and projection state StickyNoteView, Projection
StickyNoteEntity Anchored entity that creates its own view Entity, HasAnchoring, HasScreenSpaceView
StickyNoteView Blurred text-view container; remembers drag offsets and lastFrame UITextView
MessageLabel Timed feedback label with an ignoreMessages switch DispatchQueue.main

Observed: HasScreenSpaceView has one conformer, but its extension holds all the screen-positioning logic, so ViewController calls note.updateScreenPosition() without knowing the component layout.

Access control

Symbol Access Verified effect Likely rationale
insertNewSticky(_:), dismissKeyboard(), panStickyNote, attemptRepositioning, trashZoneThresholdFeedback (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:47, ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:172) fileprivate Callable only from the gestures file Inference: the @objc gesture handlers are the entry points; the steps behind them stay local.
setupShadeView(), setupTrashZone(), addResetButton(), addCoachingOverlay() (ScreenSpace-Sample/ViewController/Views/ViewController+OverlayUI.swift:31) fileprivate Only overlayUISetup() in the same file can call them Inference: one public-to-module setup entry point.
clearPlaceholderText, focusOnStickyView, unfocusOnStickyView (ScreenSpace-Sample/ViewController/Delegates/ViewController+UITextViewDelegate.swift:56) fileprivate Local to the text-delegate file Inference: helper steps of the delegate callbacks.
setupBlurViewContainer(), setupTextView() (ScreenSpace-Sample/ViewController/Views/StickyNoteView.swift:49) fileprivate Local to StickyNoteView.swift Inference: view construction details.
animateStickyViewToEditingFrame(_:keyboardHeight:) (ScreenSpace-Sample/ViewController/Delegates/ViewController+UITextViewDelegate.swift:79) implicit internal Called from Keyboard+Helpers.swift as well Inference: shared between two extension files, so it cannot be fileprivate.
ViewController stored properties (ScreenSpace-Sample/ViewController/ViewController.swift:19) implicit internal Every extension file reads and writes them Inference: one-module sample; no private state.

Reference code

ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:164 — internal delete used by gestures and reset

extension ViewController {
    // ...
    func deleteStickyNote(_ note: StickyNoteEntity) {
        guard let index = stickyNotes.firstIndex(of: note) else { return }
        note.removeFromParent()
        stickyNotes.remove(at: index)
        note.view?.removeFromSuperview()
        note.view?.isInTrashZone = false
    }
    // ...
}

Swift fileprivate here is the meaningful boundary: each extension file hides its helper steps from the others. No declaration in the sample is private or public.

Logic ownership and placement

Logic Owning type or file Placement rationale
ARKit support check AppDelegate.application(_:didFinishLaunchingWithOptions:) Calls fatalError when world tracking is unsupported (ScreenSpace-Sample/AppDelegate.swift:16).
Create a note ViewController.insertNewSticky(_:) Raycasts the tap location against estimated planes, creates the entity, adds it to the scene, and inserts its view (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:53).
Visibility and position ViewController.updateScene(on:) and HasScreenSpaceView.updateScreenPosition() A dot product with the camera’s forward axis decides visibility (ScreenSpace-Sample/ViewController/ViewController.swift:73).
Drag and delete ViewController.panStickyNote Moves the view directly, tracks whether it is over trashZone, then deletes or re-raycasts on .ended (ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift:105).
Editing ViewController text-delegate extension Marks the entity as editing and animates the view to a keyboard-aware frame (ScreenSpace-Sample/ViewController/Delegates/ViewController+UITextViewDelegate.swift:13).
Reset ViewController.reset() Re-runs the current session configuration with .removeExistingAnchors and deletes every note (ScreenSpace-Sample/ViewController/ViewController.swift:82). The source never builds its own configuration.
Coaching ViewController coaching extension Disables interaction and ends editing while the overlay is active (ScreenSpace-Sample/ViewController/Delegates/ViewController+ARCoachingOverlayDelegate.swift:12).

Design patterns

Pattern Source evidence Purpose or tradeoff
View-controller organization ViewController owns the note list, subscription, and overlays (ScreenSpace-Sample/ViewController/ViewController.swift:27) and is split into extension files by concern One controller coordinates the experience; no separate model or view-model type exists.
Protocol-oriented abstraction HasScreenSpaceView: Entity with an extension that supplies accessors and positioning (ScreenSpace-Sample/ViewController/Components/ScreenSpaceComponent.swift:11, ScreenSpace-Sample/ViewController/Components/ScreenSpaceComponent.swift:83) Any entity that stores a ScreenSpaceComponent gains screen-annotation behavior. Today only StickyNoteEntity conforms.
Delegate or data-source callbacks UITextViewDelegate, ARSessionDelegate, ARCoachingOverlayViewDelegate on ViewController (ScreenSpace-Sample/ViewController/Delegates/ViewController+UITextViewDelegate.swift:11, ScreenSpace-Sample/ViewController/Delegates/ViewController+ARCoachingOverlayDelegate.swift:10) Framework events flow back to the single controller.

No entity-component-system label is claimed: ScreenSpaceComponent is a stored property, not a registered component processed by a RealityKit System.

Naming conventions

  • Types: StickyNoteEntity and StickyNoteView pair the domain noun with the layer (RealityKit entity, UIKit view). The protocol uses RealityKit’s Has… prefix (HasScreenSpaceView, matching HasAnchoring), and the component ends in Component.
  • Extension files use ViewController+<Concern>.swift, named after the protocol (+UITextViewDelegate, +ARCoachingOverlayDelegate) or the area (+Gestures, +OverlayUI).
  • Methods: gesture handlers use past tense (tappedOnARView, swipedDownOnARView, panOnStickyView, tappedReset). Setup methods end in Setup (arViewGestureSetup, overlayUISetup).
  • Booleans use is… and should… (isDragging, isEditing, isInTrashZone, shouldAnimate).

Architecture takeaways

  • A per-frame scene-event subscription is the bridge between world space and screen space; skip objects whose screen position the user currently controls.
  • Keeping the UIKit view inside a component, with a weak back-reference from view to entity, ties the two lifetimes together without a cycle.
  • A constrained protocol with a default extension (HasScreenSpaceView: Entity) packages reusable behavior for entities without subclassing.
  • fileprivate helpers per extension file give a single large controller some internal structure.
  • Lifetimes are implicit: the subscription and the keyboard observer are never explicitly cancelled or removed, which is acceptable only because the controller lives for the whole app.

Source map

Source file Relevant symbols
ScreenSpace-Sample/ViewController/ViewController.swift ViewController, subscription, updateScene(on:), reset(), session(_:didFailWithError:)
ScreenSpace-Sample/ViewController/Components/ScreenSpaceComponent.swift HasScreenSpaceView, updateScreenPosition(), ScreenSpaceComponent, Projection
ScreenSpace-Sample/ViewController/Entities/StickyNoteEntity.swift StickyNoteEntity
ScreenSpace-Sample/ViewController/Views/StickyNoteView.swift StickyNoteView, stickyNote
ScreenSpace-Sample/ViewController/Views/MessageLabel.swift MessageLabel, displayMessage(_:duration:)
ScreenSpace-Sample/ViewController/Views/ViewController+OverlayUI.swift overlayUISetup(), addCoachingOverlay()
ScreenSpace-Sample/ViewController/Gestures/ViewController+Gestures.swift insertNewSticky(_:), panStickyNote, deleteStickyNote(_:), attemptRepositioning
ScreenSpace-Sample/ViewController/Delegates/ViewController+UITextViewDelegate.swift textViewDidBeginEditing(_:), animateStickyViewToEditingFrame
ScreenSpace-Sample/ViewController/Delegates/ViewController+ARCoachingOverlayDelegate.swift coachingOverlayViewWillActivate(_:)
ScreenSpace-Sample/ViewController/Utilities/Keyboard+Helpers.swift keyboardIsPoppingUp(notification:)
ScreenSpace-Sample/AppDelegate.swift AppDelegate
ScreenSpace-Sample/Info.plist Scene manifest
ScreenSpace-Sample.xcodeproj/project.pbxproj Deployment target, device family