How to use Metal with a UIView in Swift

Oscar de la Hera Gomez
Three flowers that represent Swift, Metal and XCode side by side with the text "Setup Metal with a UIView" beneath them.

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

A screenshot of Xcode showing the files that we created for the custom UIView. The code for each of the extensions is found below.

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

A screenshot of Xcode showing the code for the sample 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

A screenshot of Xcode showing the files that we touched to add the UIView to the 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

A screenshot of an iPhone showing a black background with a red triangle that was produced with metal.

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.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details