How to use Metal with a UIView in Swift


A step by step guide on setting up a MTKView, Metal Shader and associated files to work within a UIView, through the example of a Triangle.
We recommend that you clone our Open Source Swift Starter Project, checking out the main branch and carrying out the steps below. The changes can be found on the tutorial/metal/setup branch.
git clone git@github.com:delasign/swift-starter-project.git
Step One: Create a Custom UIView

Create a custom UIView called MetalView.swift as well as two extension files MetalView+UI.swift and MetalView+MetalDelegate.swift, and paste in the relevant code provided below.
A | MetalView.swift
B | MetalView+UI.swift
C | MetalView+MetalDelegate.swift
Step Two: Create the Metal Shader

Under the UI folder, create a new folder called Shaders.
Within the Shaders folder, create a new file called SampleMetalShader.metal and copy the code below.
Step Three: Add to UIViewController

In the ViewController.swift declare the MetalView along with its constraints.
Add the MetalView to the UI in the ViewController+UI.swift extension.
Finally, in the ViewController+Update.swift extension, add functionality to make the MetalView update safe area constraints as the device changes orientation.
Step Four: Test

Run the code on a device and confirm that you see a triangle.
Looking to learn more about things you can do with Swift, Metal and XCode ?
Search our blog to find educational content on learning how to use Swift, Metal and XCode.