[英]Calling SwiftUI View from UITabBarController
我正在慢慢地將我的項目轉換為 SwiftUI。 我想將故事板中的 UITabBarController 連接到 SwiftUI 視圖。
我的理解是最好的方法是使用 UIHostingController。 我在我的故事板中添加了一個,將它連接到 TabBar,並將我的自定義 HostingViewController 作為自定義類添加到該控制器。 (這確實顯示在“更多”選項卡下,如果這很重要的話)
我假設我在這里遺漏了一些代碼,但我發現大部分代碼片段都缺少正確的示例。 主機控制器
import Foundation
import UIKit
import SwiftUI
class HseEventHostingVC: UIHostingController<HseView>{
}
我已將其設置為故事板中 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)
}
}
}
以及我的 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
}
更新:我嘗試在 Hosting 控制器之前添加一個導航控制器,但我得到了一個黑屏。
能夠解決這個問題,我認為其他人最終會需要它。
關鍵是在定義我的 UIHostController 時,我必須用我的 SwiftUI 視圖正確地初始化它
class MyClassNameHostVC: UIHostingController<CustomSwiftUiView>{
required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder, rootView: CustomSwiftUiView())
}
}
幫助從這個站點解決了這個問題..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.