Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metal iOS gives compile error

Tags:

ios

swift

metal

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?

like image 351
Pocketkid2 Avatar asked Oct 03 '15 00:10

Pocketkid2


2 Answers

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.

like image 174
Rhythmic Fistman Avatar answered Oct 07 '22 20:10

Rhythmic Fistman


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.

like image 24
nevyn Avatar answered Oct 07 '22 20:10

nevyn