错误:枚举大小写要求闭包符合“视图”

时间:2020-02-06 10:13:35

标签: swift swiftui

我希望创建一个以SwiftUI视图作为子视图的UIViewRepresentable,我有以下代码,可以将其粘贴到Xcode中一个空SwiftUI项目的ContentView上。

enum Action现在只有一个大小写,但是它是添加将在updateUIView()中执行的其他操作的钩子。

import SwiftUI

struct LegacyView<Content: View>: UIViewRepresentable {
    enum Action {
        case idle
    }

    @Binding var action: Action
    let content: Content

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UIView {
        let hosting = UIHostingController(rootView: self.content)
        let legacyView = UIView()
        legacyView.addSubview(hosting.view)
        hosting.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        return legacyView
    }

    func updateUIView(_ uiView: UIView, context: Context) {
    }

    class Coordinator: NSObject {
        let parent: LegacyView

        init(_ parent: LegacyView) {
            self.parent = parent
        }
    }
}

struct ContentView: View {
    var body: some View {
        LegacyView(action: .constant(.idle)) {
            Text("Hello, world!")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

但是,在body的{​​{1}}的第一行,出现以下错误:ContentView。该错误如何解决?

1 个答案:

答案 0 :(得分:2)

根据LegacyView中的预期用法,此处已纠正ContentView的代码...

struct LegacyView<Content: View>: UIViewRepresentable {
    enum Action {
        case idle
    }

    @Binding var action: Action
    let content: () -> Content // << builder type

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UIView {
        let hosting = UIHostingController(rootView: self.content()) // << used builder
        let legacyView = UIView()
        legacyView.addSubview(hosting.view)
        hosting.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        return legacyView
    }

    func updateUIView(_ uiView: UIView, context: Context) {
    }

    class Coordinator: NSObject {
        let parent: LegacyView

        init(_ parent: LegacyView) {
            self.parent = parent
        }
    }
}