我正在学习并使用图形API metal制作一个简单的应用程序,我试图让我的视图控制器从UIKit显示在SwiftUI中。我试图让UIViewControllerRepresentable从我的ViewController类中出来,但这一直导致类型“UIViewController”的错误不符合协议“UIViewControllerRepresentable”。这很可能是因为我的ViewController现在抛出了一个非协议继承的错误,非类类型'UIViewController',所以它没有协议。那么我如何使包含所有金属代码的ViewController采用可表示对象所需的协议?
下面是我代码:
//ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
UIViewController()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
//UIViewController.swift
import SwiftUI
import UIKit
struct UIViewController: UIViewControllerRepresentable { //error: Type 'UIViewController' does not conform to protocol 'UIViewControllerRepresentable'
func makeUIViewController(context: Context) -> ViewController{
return ViewController()
}
}
struct UIViewController_Previews: PreviewProvider {
static var previews: some View {
UIViewController()
}
}
//ViewController.swift
import UIKit
import Metal
class ViewController: UIViewController { //error: Inheritance from non-protocol, non-class type 'UIViewController'
var device: MTLDevice!
var metalLayer: CAMetalLayer!
//created is the buffer to send the points over to gpu
var vertexBuffer: MTLBuffer!
//starts the render pipeline
var pipelineState: MTLRenderPipelineState!
//command queue
var commandQueue: MTLCommandQueue!
//timer to render the screen frame by frame
var timer: CADisplayLink!
//insuring the view is loaded so the device can actually be used
override func viewDidLoad() { //error: Method does not override any method from its superclass
super.viewDidLoad()
device = MTLCreateSystemDefaultDevice()
metalLayer = CAMetalLayer()
metalLayer.device = device
metalLayer.pixelFormat = .bgra8Unorm
metalLayer.framebufferOnly = true
metalLayer.frame = view.layer.frame
view.layer.addSublayer(metalLayer) //error: Use of unresolved identifier 'view'
....
ViewController中没有错误,直到我尝试在SwiftUI中显示它。
很抱歉作为一个完全的初学者在IOS开发和图形,但感谢您的帮助提前。
2条答案
按热度按时间piztneat1#
对于错误
类型“UIViewController”不符合协议“UIViewControllerRepresentable”
我猜你错过了
UIViewControllerRepresentable
协议中的方法 updateUIViewController另外,调用结构
UIViewController
* 可能 * 会导致一些名称冲突yfjy0ee72#
在UIViewControllerRepresentable中实现两个协议方法:makeUIViewController和updateUIViewController。然后在第二个中,如果你想使用它(或其他你想要的类),确保将你的控制器转换为UIPageViewController。像这样: