Apple’s ‘Using Metal to Draw a View’s Contents’ in Swift

less than 1 minute read

Introductory resources for Metal, Apple’s low level graphics API, are typically geared towards 3D games and scenes. In this post, I’ll translate Apple’s Using Metal to Draw a View’s Contents MetalKit sample from Objective-C to Swift, seeking to balance changing as little as possible with a ‘Swift-y’ approach.

metalView.device = MTLCreateSystemDefaultDevice()
metalView.clearColor = MTLClearColorMake(0.0, 0.5, 1.0, 1.0)
metalView.enableSetNeedsDisplay = true

The first three lines are trivial enough. But where to put them? Many of Apple’s samples simple opt for trusty ‘viewDidLoad’. Let’s instead override UIKit’s ‘loadView’ function:

override func loadView() {
    metalView.device = MTLCreateSystemDefaultDevice()
    metalView.clearColor = MTLClearColorMake(0.0, 0.5, 1.0, 1.0)
    metalView.enableSetNeedsDisplay = true
    metalView.delegate = renderer

    view = metalView
}

We’ll keep strong references to the MTKView and our renderer in the ViewController:

private let metalView = MTKView()
private lazy var renderer = BlankRenderer(view: metalView)