MetalKit, MTKView and SwiftUI

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Metal draws into textures; something else has to turn a texture into a window on the screen. That something is a Core Animation layer called CAMetalLayer, and MetalKit’s MTKView is the ready-made view that owns one, hands you a drawable each frame, creates the depth and multisample textures you ask for, and calls your code at the display’s pace. This page explains what MTKView does for you and what it does not, how to host it inside SwiftUI on every Apple platform, how to drive a CAMetalLayer yourself with CAMetalDisplayLink when you need tighter control, and how to keep the CPU and GPU from stepping on each other’s data with frames in flight.

The facts were checked in November 2026. The versions documented are MetalKit as shipped with the 26 operating systems (the Metal 4 members currentMTL4RenderPassDescriptor since 26.0 and residencySet since 26.4 are marked where used), CAMetalLayer and CAMetalDisplayLink (iOS 17, macOS 14, visionOS 1.0 and later), SwiftUI’s UIViewRepresentable and NSViewRepresentable, and Swift 6. The examples run on iOS, iPadOS, macOS and tvOS, and on visionOS inside a window; immersive rendering on visionOS uses Compositor Services instead (see Metal on visionOS). The Metal 4 core objects used by the renderers are introduced in Hello Triangle with Metal 4.

This is the second step of the Metal Bookshelf running example: the multiplatform SwiftUI app that hosts the MTKView. Everything later in the section (textured book, shelf, shadows, particles) renders through the delegate described here. The general concept of a game loop and how frame time is budgeted is in Game Loop and Frame Timing.

Where MTKView sits

Flow diagram: SwiftUI view, representable and coordinator, the MTKView with its delegate, the renderer and command queue, the GPU, the CAMetalLayer with its drawable pool, and the display
Figure 1. The path from a SwiftUI value to the display, with the object that owns each link

MTKView is a UIView on iOS, iPadOS, tvOS and visionOS and an NSView on macOS. Behind it is a CAMetalLayer, which keeps a small pool of drawables. A drawable (CAMetalDrawable) is a texture that is shared with the display subsystem: you render into drawable.texture and present the drawable, and Core Animation shows it at the next refresh. Two properties of the pool shape everything else on this page: it is small (two or three drawables), and when all of them are in use nextDrawable() blocks the calling thread, usually until the next refresh.

What MTKView does:

  • creates and resizes the CAMetalLayer and its drawables when the view’s size or scale changes;

  • creates the depth/stencil texture and the multisample colour texture when depthStencilPixelFormat or sampleCount ask for them;

  • builds a render pass descriptor (currentRenderPassDescriptor, or currentMTL4RenderPassDescriptor for Metal 4) that targets the current drawable, with a clear action and the view’s clearColor;

  • calls your delegate at the rate and in the mode you choose.

What it does not do: it does not create a command queue, pipelines or buffers, it does not present the drawable (you do), and it does not keep your renderer alive.

Property reference

Property Default What it does and when to change it

device

nil

The MTLDevice the view’s resources are created on. It must be set before the first draw. preferredDevice reports the device the system would pick for the screen the view is on, which matters on Macs with more than one GPU.

colorPixelFormat

.bgra8Unorm

Format of the drawables. .bgra8Unorm_srgb makes the hardware convert linear shader output to sRGB on write. .rgba16Float with an extended-range colour space and CAMetalLayer.wantsExtendedDynamicRangeContent gives EDR output, see Image-Based Lighting and HDR. Your pipeline’s colorAttachments[0].pixelFormat must match this value.

colorspace

system default

The CGColorSpace that tags the drawable content. Leave it unless you render in Display P3 or an extended linear space.

framebufferOnly

true

True lets Core Animation and the GPU use the most efficient layout and forbids sampling or reading the drawable texture. Set false only if you must read it in a later pass or capture it, and expect a cost.

drawableSize, autoResizeDrawable, preferredDrawableSize

view size times the screen scale; true

With auto-resize on, the drawable follows the view’s pixel size and the delegate hears about it in mtkView(_:drawableSizeWillChange:). Turn it off to render at a fixed lower resolution and let the system scale (then set drawableSize yourself), a common way to cut fill cost.

clearColor, clearDepth, clearStencil

black, 1.0, 0

Values the generated descriptor uses for its clear load actions. For reversed-Z depth set clearDepth to 0.

depthStencilPixelFormat

.invalid (no depth)

Set to .depth32Float (or .depth32Float_stencil8, .depth16Unorm) to get a depth texture. depthStencilAttachmentTextureUsage and depthStencilStorageMode control its usage and storage; the texture is available as depthStencilTexture.

sampleCount

1

Set to 4 (supported on all Apple GPUs) for MSAA. The view then creates a multisample colour texture and resolves into the drawable. multisampleColorAttachmentTextureUsage adds usage flags.

preferredFramesPerSecond

60

The rate requested from the display link. The view clamps to what the display supports (for example 120 on ProMotion displays), and the actual rate can be lower when drawing takes longer than the frame interval.

isPaused, enableSetNeedsDisplay

false, false

Select the drawing mode, below.

presentsWithTransaction

false

True synchronises presentation with Core Animation transactions, which is only needed when Metal content must change in step with UIKit or AppKit layout; it adds latency, so leave it off for games.

currentDrawable

read-only

The drawable for the frame. Reading it may block; read it as late as possible. Returns nil if none is available.

currentRenderPassDescriptor, currentMTL4RenderPassDescriptor

read-only

A pass descriptor for the Metal 3 or the Metal 4 encoders (the Metal 4 property is available from 26.0). Reading either obtains the drawable implicitly.

residencySet

read-only (26.4)

The residency set of the view’s drawable resources. In Metal 4, add it to your queue (or use CAMetalLayer.residencySet, available from 26.0).

releaseDrawables()

-

Frees the drawables and attached textures; call it when the view will be hidden for a long time to return memory.

The three drawing modes

Three columns: timed updates, draw on demand and explicit draw, each with the isPaused and enableSetNeedsDisplay values and the resulting behaviour of draw
Figure 2. The MTKView drawing modes and the properties that select them
  • Timed updates (the default): isPaused = false and enableSetNeedsDisplay = false. The view calls draw(in:) at preferredFramesPerSecond. This is the mode for anything that animates.

  • Draw on demand: isPaused = true and enableSetNeedsDisplay = true. The view draws only when the system or you mark it dirty with setNeedsDisplay() (UIKit) or needsDisplay = true (AppKit). It suits editors, viewers and tools where nothing moves between edits, and it costs no battery while idle.

  • Explicit draw: isPaused = true and enableSetNeedsDisplay = false. You call view.draw() yourself, for example from your own display link or after a capture trigger.

Either implement MTKViewDelegate or subclass MTKView and override draw(_:), but not both.

flowchart TD A{"Does the content animate every frame?"} -- no --> B["Draw on demand: isPaused true, enableSetNeedsDisplay true"] A -- yes --> C{"Need to control the presentation time or latency?"} C -- no --> D["Timed updates with MTKView, preferredFramesPerSecond"] C -- yes --> E["CAMetalLayer with CAMetalDisplayLink, own run loop"] D --> F{"Need the render thread off the main thread?"} F -- yes --> E F -- no --> G["Keep MTKView draw(in:) on the main thread"]
Figure 3. Choosing how to drive the frames

The delegate

public protocol MTKViewDelegate: NSObjectProtocol {
    func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize)
    func draw(in view: MTKView)
}
  • mtkView(_:drawableSizeWillChange:) runs when the drawable’s pixel size is about to change: on the first layout, on window resize, on a rotation or a move to a screen with another scale. It is where you recompute anything that depends on the aspect ratio (the projection matrix), and resize screen-sized render targets such as a G-buffer or a shadow-map-independent post-processing texture. The size is in pixels, not points.

  • draw(in:) is the frame. By default it is called on the main thread. Everything the frame needs from the view (currentDrawable, a render pass descriptor) must be read inside it.

Do not do per-frame work in mtkView(_:drawableSizeWillChange:), and do not assume it is called before the first draw(in:): call it yourself from the renderer’s initialiser with the view’s current drawableSize, as the examples do.

Hosting an MTKView in SwiftUI

SwiftUI has no Metal view, so you wrap MTKView in a representable. The wrapper must do four things: create the view, configure it, keep the renderer alive (the view’s delegate is a weak reference), and forward SwiftUI state to the view in the update call.

Storyboard of five panels: the app scene, the representable, the coordinator holding the renderer, makeView configuring the MTKView, and the view driving the draw loop
Figure 4. The wiring of the representable, the coordinator and the renderer, step by step
import SwiftUI
import MetalKit

#if os(macOS)
typealias PlatformRepresentable = NSViewRepresentable
#else
typealias PlatformRepresentable = UIViewRepresentable
#endif

/// A SwiftUI view that renders with Metal through an MTKView.
struct MetalView: PlatformRepresentable {
    /// State that SwiftUI pushes into the view.
    var isPaused = false
    var framesPerSecond = 60

    /// Owns the renderer: MTKView.delegate does not retain it.
    final class Coordinator {
        var renderer: (any MTKViewDelegate)?
    }
    func makeCoordinator() -> Coordinator { Coordinator() }

    private func makeMetalView(context: Context) -> MTKView {
        let view = MTKView()
        guard let device = MTLCreateSystemDefaultDevice() else { return view }
        view.device = device
        view.colorPixelFormat = .bgra8Unorm
        view.depthStencilPixelFormat = .invalid          // set .depth32Float once a pass needs depth
        view.clearColor = MTLClearColor(red: 0.08, green: 0.08, blue: 0.1, alpha: 1)
        view.clearDepth = 1.0
        view.sampleCount = 1
        view.framebufferOnly = true
        context.coordinator.renderer = makeRenderer(for: view)   // from the previous page
        view.delegate = context.coordinator.renderer
        updateMetalView(view)
        return view
    }

    private func updateMetalView(_ view: MTKView) {
        view.isPaused = isPaused
        view.preferredFramesPerSecond = framesPerSecond
    }

    #if os(macOS)
    func makeNSView(context: Context) -> MTKView { makeMetalView(context: context) }
    func updateNSView(_ view: MTKView, context: Context) { updateMetalView(view) }
    #else
    func makeUIView(context: Context) -> MTKView { makeMetalView(context: context) }
    func updateUIView(_ view: MTKView, context: Context) { updateMetalView(view) }
    #endif
}

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase
    @State private var userPaused = false

    var body: some View {
        MetalView(isPaused: userPaused || scenePhase != .active, framesPerSecond: 60)
            .ignoresSafeArea()
            .overlay(alignment: .topTrailing) {
                Toggle("Pause", isOn: $userPaused)
                    .toggleStyle(.button)
                    .padding()
            }
    }
}

Notes on this host:

  • Why a coordinator. A SwiftUI view is a short-lived value that SwiftUI recreates freely; the coordinator is the one object SwiftUI keeps for the lifetime of the underlying platform view, so it is the right owner of the renderer. Storing the renderer in a property of the struct would create a new renderer (and recompile pipelines) whenever SwiftUI rebuilt the value.

  • updateView runs often. SwiftUI calls it whenever the view’s inputs change. Only set cheap properties there; never create Metal objects in it.

  • Pausing. The scene phase becomes inactive or background when the app is not visible; drawing then wastes power, and iOS does not permit submitting GPU work from the background. On macOS scenePhase also turns inactive when the window loses focus, so a game may prefer to keep running there.

  • Platforms. UIViewRepresentable works on iOS, iPadOS, tvOS and visionOS windows; a visionOS window shows the MTKView as a flat surface. For stereo, immersive content use Compositor Services.

  • Previews. Keep the Metal setup in the renderer, not in the view’s initialiser, so a failed device creation does not crash a preview. The code above returns a plain MTKView when no device exists.

The project setup (a multiplatform target, shared files, platform-conditional code) is described in Multiplatform Projects and Xcode Projects and Previews.

Resizing, scale and pixel formats

Points are layout units; the drawable is in pixels. On a 3x iPhone a 400-point-wide view has a 1,200-pixel-wide drawable. The delegate reports pixels, the viewport is in pixels, and the projection’s aspect ratio is width / height of the drawable, so a renderer that uses the view’s bounds for those gets blurry or distorted output on Retina screens.

func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
    aspect = Float(size.width / max(size.height, 1))      // avoid division by zero while collapsed
    projection = perspective(fovy: .pi / 3, aspect: aspect, near: 0.1, far: 100)
    resizeScreenSizedTargets(width: Int(size.width), height: Int(size.height))
}

A size of zero in either dimension can arrive while a window is being created or collapsed; guard against it, because creating a zero-sized texture fails. To render below native resolution, set autoResizeDrawable = false and drawableSize to the smaller size; the system scales the result to the view, which is how fixed-resolution games and dynamic resolution scaling are done. MetalFX upscaling (see MetalFX Upscaling and Frame Interpolation) is the higher-quality version of the same idea.

Frames in flight and triple buffering

Timeline with three rows for CPU, GPU and display; each frame moves from CPU encoding to GPU rendering to display, with colours showing the slot each frame uses and a dashed note where frame 4 waits to reuse slot 1
Figure 5. Three frames overlap: the CPU encodes frame N while the GPU renders N minus 1 and the display shows N minus 2

The CPU and the GPU work in parallel, one frame apart. That is only safe if the CPU never writes a buffer the GPU is still reading. The standard solution is a ring of per-frame resources: one uniform buffer region, one command allocator (Metal 4) and any other per-frame data for each of k frames in flight, and a counter that stops the CPU from running more than k frames ahead. Using the frame number \( n \), the slot is \( n \bmod k \), and frame \( n \) may start only after frame \( n - k \) has finished on the GPU.

Choosing k:

  • k = 1 serialises the CPU and GPU: the GPU idles while the CPU encodes and the reverse. Simple, but frame time is the sum of both.

  • k = 2 is double buffering: the CPU and GPU overlap, but any CPU hiccup stalls the GPU because there is no spare frame.

  • k = 3 is triple buffering and the value Apple’s samples use. It absorbs spikes at the price of up to one extra frame of input latency.

  • Higher values only help when frames vary wildly; they cost memory and latency. The drawable pool (maximumDrawableCount, 2 or 3) is a separate limit that also blocks nextDrawable().

A reusable ring for small per-frame structs, usable with both Metal generations:

import Metal

/// One shared buffer holding `frames` aligned copies of T, one per frame in flight.
struct UniformRing<T> {
    let buffer: MTLBuffer
    let slotStride: Int
    let frames: Int

    init?(device: MTLDevice, frames: Int = 3) {
        // 256 bytes satisfies the constant-buffer offset alignment of every Apple GPU;
        // the Metal Feature Set Tables list the actual minimum per family.
        let aligned = (MemoryLayout<T>.stride + 255) & ~255
        guard let buffer = device.makeBuffer(length: aligned * frames, options: .storageModeShared) else { return nil }
        self.buffer = buffer
        self.slotStride = aligned
        self.frames = frames
    }

    /// Byte offset of the slot used by `frameNumber`.
    func offset(for frameNumber: UInt64) -> Int { Int(frameNumber % UInt64(frames)) * slotStride }

    /// Copies `value` into the slot for `frameNumber` and returns the GPU address of that slot.
    @discardableResult
    func write(_ value: T, frame frameNumber: UInt64) -> MTLGPUAddress {
        let slotOffset = offset(for: frameNumber)
        buffer.contents().advanced(by: slotOffset).storeBytes(of: value, as: T.self)
        return buffer.gpuAddress + UInt64(slotOffset)
    }
}

// Metal 3: encoder.setVertexBuffer(ring.buffer, offset: ring.offset(for: frame), index: 1)
// Metal 4: argumentTable.setAddress(ring.write(uniforms, frame: frame), index: 1)

The wait itself depends on the API generation. Metal 3 renderers use a DispatchSemaphore created with the count k, waited on at the start of draw(in:) and signalled from the command buffer’s completed handler. Metal 4 renderers use an MTLSharedEvent: the queue signals the frame number when the frame’s commands finish and the CPU waits on frameNumber - k. Both versions are written out in Hello Triangle with Metal 4, and the general synchronisation tools (fences, events, barriers) are in Synchronization and Barriers.

On Apple silicon, buffers in .storageModeShared live in memory that both processors can address, so no copy is needed. Per-frame data larger than 4 KB goes in a buffer from the ring; smaller data may use setVertexBytes or setFragmentBytes in Metal 3, which copy the bytes into the command stream. Metal 4 encoders have no equivalent, so small constants also live in a ring slot.

Driving a CAMetalLayer yourself

MTKView is a convenience. When you need to render on a non-main thread, choose the presentation timing, or avoid a UI view altogether, use a CAMetalLayer directly. The layer’s own properties:

Property Effect

device, pixelFormat, colorspace

As on MTKView. pixelFormat supports a limited set (for example .bgra8Unorm, .bgra8Unorm_srgb, .rgba16Float, .bgr10_xr, .rgb10a2Unorm).

drawableSize

Pixel size of the drawables. Update it when the view’s bounds or scale change; unlike MTKView, the layer does not do it for you.

framebufferOnly

True by default: the drawable texture can only be a render target. Set false to sample or blit from it.

maximumDrawableCount

2 or 3 (the default is 3). Two lowers latency and memory, three keeps the GPU busier.

allowsNextDrawableTimeout

True by default: nextDrawable() returns nil if it cannot provide a drawable within one second instead of blocking forever. Handle nil by skipping the frame.

displaySyncEnabled

On macOS, false lets drawables present without waiting for the display refresh (tearing is possible); useful for benchmarks.

presentsWithTransaction

As on MTKView.

wantsExtendedDynamicRangeContent, edrMetadata

Opt in to HDR/EDR content with an extended-range pixel format and colour space.

developerHUDProperties

Configure the Metal Performance HUD for this layer.

residencySet

(26.0) The residency set of the layer’s drawables; add it to an MTL4CommandQueue.

A layer-backed view for both UIKit and AppKit:

import QuartzCore
import Metal

#if os(macOS)
import AppKit
final class MetalLayerView: NSView {
    override init(frame: NSRect) { super.init(frame: frame); wantsLayer = true }
    required init?(coder: NSCoder) { super.init(coder: coder); wantsLayer = true }
    override func makeBackingLayer() -> CALayer { CAMetalLayer() }
    var metalLayer: CAMetalLayer { layer as! CAMetalLayer }
}
#else
import UIKit
final class MetalLayerView: UIView {
    override class var layerClass: AnyClass { CAMetalLayer.self }
    var metalLayer: CAMetalLayer { layer as! CAMetalLayer }
}
#endif

CADisplayLink tells you a refresh is coming. CAMetalDisplayLink (iOS 17, macOS 14, visionOS 1.0) is specialised for Metal layers: it hands you the drawable for the update together with the time it is expected to be shown, and it lets you choose how much latency to trade for smoothness.

sequenceDiagram participant D as Display participant L as CAMetalDisplayLink participant A as App delegate participant G as GPU D->>L: refresh approaching L->>A: metalDisplayLink needsUpdate with drawable and target timestamps A->>A: update simulation for the target presentation time A->>G: encode, present drawable, commit G-->>D: drawable shown at the target time Note over L,A: preferredFrameLatency sets how far ahead updates are requested
Figure 6. The callbacks of a Metal display link
import QuartzCore
import Metal

/// Clears a CAMetalLayer to a colour that pulses with the presentation time.
final class DisplayLinkRenderer: NSObject, CAMetalDisplayLinkDelegate {
    private let device: MTLDevice
    private let queue: MTLCommandQueue
    private var link: CAMetalDisplayLink?

    init?() {
        guard let device = MTLCreateSystemDefaultDevice(),
              let queue = device.makeCommandQueue() else { return nil }
        self.device = device
        self.queue = queue
    }

    /// Call on the main thread once the layer has its final size.
    func start(on layer: CAMetalLayer) {
        layer.device = device
        layer.pixelFormat = .bgra8Unorm
        layer.framebufferOnly = true
        layer.maximumDrawableCount = 3

        let link = CAMetalDisplayLink(metalLayer: layer)
        link.delegate = self
        link.preferredFrameLatency = 2                       // frames of latency the system should allow
        link.preferredFrameRateRange = CAFrameRateRange(minimum: 30, maximum: 120, preferred: 60)
        link.add(to: .main, forMode: .common)                // callbacks arrive on this run loop
        self.link = link
    }

    func stop() {
        link?.invalidate()
        link = nil
    }

    func metalDisplayLink(_ link: CAMetalDisplayLink, needsUpdate update: CAMetalDisplayLink.Update) {
        let drawable = update.drawable
        let pulse = Float(0.5 + 0.5 * sin(update.targetPresentationTimestamp))

        let pass = MTLRenderPassDescriptor()
        pass.colorAttachments[0].texture = drawable.texture
        pass.colorAttachments[0].loadAction = .clear
        pass.colorAttachments[0].storeAction = .store
        pass.colorAttachments[0].clearColor = MTLClearColor(red: 0.1, green: Double(pulse) * 0.4, blue: 0.5, alpha: 1)

        guard let commandBuffer = queue.makeCommandBuffer(),
              let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass) else { return }
        encoder.endEncoding()
        commandBuffer.present(drawable)
        commandBuffer.commit()
    }
}

Details that matter:

  • The delegate gets a CAMetalDisplayLink.Update with drawable, targetTimestamp and targetPresentationTimestamp. Use the presentation timestamp to advance animation, so motion stays smooth even when a frame is late.

  • preferredFrameRateRange is a request; the system picks a rate inside it. preferredFrameLatency is how many frames of latency you accept; lower is more responsive but leaves less time to render.

  • The callback arrives on the run loop you added the link to. Add it to a background thread’s run loop to render off the main thread.

  • isPaused stops callbacks without destroying the link; invalidate() removes it from all run loops and must be called before the layer or the renderer goes away.

  • The documentation asks you to finish the queue commits for the layer before presenting the drawable, so keep encode, commit and present together in the callback.

Lifecycle, memory and power

  • Pause when invisible. Set isPaused (or pause the display link) when the scene is inactive, minimised or covered. A paused view draws nothing and keeps its last drawable on screen.

  • Release memory. releaseDrawables() frees the drawables and attached textures; the view recreates them on the next draw.

  • Frame rate. A fixed 60 or 30 frames per second saves power relative to uncapped drawing. On displays with variable refresh, ask for a range instead of a fixed rate when using CAMetalDisplayLink.

  • Direct to display. On Apple-silicon Macs, an opaque CAMetalLayer with RGB content in a full-screen window can be composited directly by the display hardware, which lowers latency and cost; the Metal Performance HUD shows whether presentation is direct or composited. Window setup for games is described in Performance Best Practices and Apple’s game-window article.

  • Simulator. Metal runs in the iOS, tvOS and visionOS Simulators on the Mac’s GPU, but the device reports capabilities similar to an older Apple family GPU, so test features such as MSAA sample counts and the Metal 4 path on hardware.

Common mistakes

Mistake Result Fix

Renderer only referenced by view.delegate

The weak delegate is released; the view draws only the clear colour or nothing

Keep a strong reference in the coordinator or the view model.

Creating the renderer in updateView or a SwiftUI body

A new device, queue and pipelines on each SwiftUI update

Create once in makeView; only set properties in updateView.

Pipeline pixel format differs from colorPixelFormat

Validation error, or black output

Read view.colorPixelFormat and depthStencilPixelFormat when building pipelines, and rebuild if they change.

Depth format set but no depth attachment used

The pass works but wastes memory and bandwidth

Leave depthStencilPixelFormat at .invalid for 2D passes.

Reading currentDrawable at the top of the frame, before heavy CPU work

The drawable is held longer, and nextDrawable() stalls other frames

Do the CPU work first, then read the drawable and descriptor.

Using bounds instead of drawableSize

Blurry or stretched output on Retina displays

Use pixel sizes for the viewport, aspect ratio and render targets.

Ignoring nil from currentDrawable

Crash on a force unwrap

Skip the frame (guard let) when no drawable or descriptor is available.

Calling Metal from draw(in:) after the view was removed

Use-after-free style crashes in teardown

Set view.delegate = nil and isPaused = true in dismantleUIView or dismantleNSView, and invalidate display links.

Performance notes

  • Draw on demand for static content, timed updates at 60 Hz for most games, and a variable range with CAMetalDisplayLink where you can use it.

  • Keep framebufferOnly true and the pixel format at .bgra8Unorm(_srgb) unless you need HDR.

  • Use sampleCount = 4 instead of higher counts; on Apple GPUs MSAA is resolved in tile memory, so it is cheap if the multisample texture can stay memoryless (see Render Passes and Load/Store Actions).

  • Never block the main thread on waitUntilCompleted; the frame-in-flight gate is the only wait a renderer needs.

  • Turn on the Metal Performance HUD (Edit Scheme, Run, Diagnostics, Show Graphics Overview, or the MTL_HUD_ENABLED=1 environment variable) to see frame interval, GPU time and whether presentation is direct.

What changed recently

Version Change

iOS 17, macOS 14 (2023)

CAMetalDisplayLink for Metal layers with control over frame latency and a rate range.

26.0 (2025)

MTKView.currentMTL4RenderPassDescriptor and CAMetalLayer.residencySet for the Metal 4 queue.

26.4

MTKView.residencySet.

27 systems (2026)

MTLStorageMode.managed is deprecated together with the Intel-only paths; MTKView itself is unchanged and remains the recommended starting point.

Where the books are out of date

Source Statement Today

Metal by Tutorials, 4th edition (chapters 1 and 3)

Requires macOS 14 and Xcode 15 and assumes every Mac since 2012 runs Metal.

Xcode 27 needs an Apple-silicon Mac on macOS 26.6 or later; Metal 4 needs an M1 or A14; MTLStorageMode.managed, MTLGPUFamily.mac2 and .common3 are deprecated in the 27 systems. For new apps, host the MTKView in SwiftUI with a representable and a coordinator that owns the renderer, and use the Metal 4 members (currentMTL4RenderPassDescriptor, residencySet) where available.

Metal Programming Guide (Clayton), chapters 3 and 8

Written for Swift 4, Xcode 9 and iOS 11; OpenGL ES is presented as the default being replaced.

OpenGL and OpenGL ES have been deprecated since iOS 12 and macOS 10.14. CAMetalDisplayLink (iOS 17, macOS 14) is the Metal-specific display link, and MTKView remains the standard starting point.