【问题标题】:Error: enum case requires that closure conforms to 'View'错误:枚举案例要求闭包符合“视图”
【发布时间】:2020-02-06 18:30:24
【问题描述】:

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

enum Action 现在只有一个 case,但它是一个钩子,用于添加将在 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()
    }
}

但是在ContentViewbody 的第一行,我收到以下错误:Enum case 'idle' requires that '() -&gt; Text' conform to 'View'。如何解决此错误?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    根据ContentView 中的预期用法,这里是LegacyView 的更正代码...

    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
            }
        }
    }
    

    【讨论】:

    • 如果答案解释问题和解决方案,而不是仅发布代码,则答案会更有帮助(对问题的作者和该线程的未来读者)。
    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 2018-12-14
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多