import UIKit
import Metal
import QuartzCore
class ViewController: UIViewController {
var device: MTLDevice! = nil
var metalLayer: CAMetalLayer! = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
device = MTLCreateSystemDefaultDevice()
metalLayer = CAMetalLayer() // 1
metalLayer.device = device // 2
metalLayer.pixelFormat = .BGRA8Unorm // 3
metalLayer.framebufferOnly = true // 4
metalLayer.frame = view.layer.frame // 5
view.layer.addSublayer(metalLayer) // 6
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When I have this in my ViewController.swift, I get the error "Use of undeclared type CAMetalLayer
" even though I've imported Metal and QuartzCore. How can I get this code to work?
UPDATE:
Simulator support is coming this year (2019)
Pre Xcode 11/iOS 13:
Metal code doesn't compile on the Simulator. Try compiling for a device.
If your app has a fallback or mode that doesn't depend on Metal, and you want to compile your app for the simulator, you can do something like this:
#if targetEnvironment(simulator)
// dummy, do-nothing view controller for simulator
class ViewController: UIViewController {
}
#else
class ViewController: UIViewController {
var device: MTLDevice! = nil
var metalLayer: CAMetalLayer! = nil
override func viewDidLoad() {
super.viewDidLoad()
device = MTLCreateSystemDefaultDevice()
metalLayer = CAMetalLayer()
...
}
}
#endif
Then your code will at least compile for both device and simulator, which can ease your non-Metal development.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With