从UITabBarController调用SwiftUI视图

斯凯达尔

我正在慢慢地将我的项目转换为SwiftUI。我想将情节提要中的UITabBarController连接到SwiftUI视图。

我的理解是最好的方法是使用UIHostingController。我在故事板上添加了一个,将其连接到TabBar,然后将自定义HostingViewController作为该控制器的自定义类添加。(如果很重要的话,这确实会显示在“更多”标签下)

我假设我在这里丢失了一些代码,但是我发现大多数片段都缺少适当的示例。UIHostingController

import Foundation
import UIKit
import SwiftUI

class HseEventHostingVC: UIHostingController<HseView>{

}

我已将其设置为故事板中的UIHostingController的类,该板已连接到我的选项卡栏。当我尝试运行时,出现此错误。

致命错误:init(coder :)必须在子类中实现,并调用super.init(coder :, rootView :):文件

在这里遵循了这个简单的指南,用于推送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 View正确初始化它

class MyClassNameHostVC: UIHostingController<CustomSwiftUiView>{
    required init?(coder aDecoder: NSCoder){
        super.init(coder: aDecoder, rootView: CustomSwiftUiView())
    }

} 

从帮助解决了这个本网站..

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章