简体   繁体   中英

Metal iOS gives compile error

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.

The same problem may appear if you name your XCode project "Metal".

In that case compiler will be confused and you'll receive the same error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM