我正在慢慢地将我的项目转换为 SwiftUI。我想将故事板中的 UITabBarController 连接到 SwiftUI 视图。
我的理解是最好的方法是使用 UIHostingController。我在我的故事板中添加了一个,将它连接到 TabBar,并将我的自定义 HostingViewController 作为自定义类添加到该控制器。(这确实显示在“更多”选项卡下,如果这很重要的话)
我假设我在这里遗漏了一些代码,但我发现大部分代码片段都缺少正确的示例。 主机控制器
import Foundation
import UIKit
import SwiftUI
class HseEventHostingVC: UIHostingController<HseView>{
}
Run Code Online (Sandbox Code Playgroud)
我已将其设置为故事板中 UIHostingController 的类,该类连接到我的标签栏。当我尝试运行时,出现此错误。
致命错误:init(coder:) 必须在子类中实现并调用 super.init(coder:, rootView:): file
我在这里遵循了这个简单的指南,这是为了推送 SwiftUI 视图,但认为它在理论上并没有太大不同。
这是我的 SwiftUI 视图
import SwiftUI
struct HseView: View {
var body: some View {
let first = HSECell(name: "Newest Observation", duedate: "2019/10/10", status: "Open", reportedBy: "Carson Skjerdal", reportedDate: "2020/01/01", hseid: "OBS12")
let hseItems = [first]
return List(hseItems) {item in
HseItemRow(hsecell: item)
}
}
}
struct HseView_Previews: PreviewProvider {
static var previews: some View {
HseView()
}
}
struct HseItemRow: View{
var hsecell: HSECell
var body: some View{
VStack{
HStack(){
Text("\(hsecell.hseid)")
Text("\(hsecell.name)")
.bold()
}
Divider()
HStack{
VStack(alignment: .leading){
Text("Reported Date: ")
.bold()
Text("Reported By: ")
.bold()
Text("Status: ")
.bold()
Text("Due Date:")
.bold()
}
VStack(alignment: .leading){
Text("\(hsecell.reportedDate)")
Text("\(hsecell.reportedBy)")
Text("\(hsecell.status)")
Text("\(hsecell.duedate)")
}
}.padding(.trailing)
}
}
}
Run Code Online (Sandbox Code Playgroud)
以及我的 HSECell 可识别结构
import Foundation
struct HSECell: Identifiable{
var id = UUID()
var name: String
var duedate: String
var status: String
var reportedBy: String
var reportedDate: String
var hseid: String
}
Run Code Online (Sandbox Code Playgroud)
更新:我尝试在 Hosting 控制器之前添加一个导航控制器,但我得到了一个黑屏。
C. *_*dal 12
能够解决这个问题,我认为其他人最终会需要它。
关键是在定义我的 UIHostController 时,我必须用我的 SwiftUI 视图正确地初始化它
class MyClassNameHostVC: UIHostingController<CustomSwiftUiView>{
required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder, rootView: CustomSwiftUiView())
}
}
Run Code Online (Sandbox Code Playgroud)
帮助从这个站点解决了这个问题..