使用Xcode 11 GM Seed编写一些SwiftUI代码,我遇到了我不明白的Swift错误。
struct MainViewController: View {
var body: some View {
VStack {
Text("Hello World!")
}
}
}
extension MainViewController : UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<MainViewController>) -> UINavigationController {
return UINavigationController()
}
func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<MainViewController>) {
}
}
此报告:
'UIViewControllerRepresentable' requires the types 'some View' and 'Never' be equivalent
答案 0 :(得分:1)
我错过了ViewController和View之间的分隔。错误是说视图控制器不能有返回视图的主体。
这有效:
struct MainView : View {
var body: some View {
VStack {
Text("Hello World!")
}
}
}
struct MainViewController : UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<MainViewController>) -> UIHostingController<MainView> {
return UIHostingController(rootView: MainView())
}
func updateUIViewController(_ uiViewController: UIHostingController<MainView>, context: UIViewControllerRepresentableContext<MainViewController>) {
}
}
然后实例化它:
let viewController = UIHostingController<MainViewController>(rootView:MainViewController())