我希望创建一个以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
。该错误如何解决?
答案 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
}
}
}