如何将SwiftUI表单添加到UIView Controller

时间:2020-08-20 10:06:55

标签: swift swiftui

我有一个UIViewController,它通过我的viewDidLoad中的一个函数来呈现:

let imageView: UIImageView = {
    let iv = UIImageView()
    iv.contentMode = .scaleAspectFit
    return iv
    }()

func configureViewComponents() {
    
    view.addSubview(imageView)

这样称呼:

override func viewDidLoad() {
    super.viewDidLoad()
    configureViewComponents()
}

我有一个单独文件格式的表单。swift:

import Combine
import SwiftUI

struct myForm: View {

@ObservedObject var submission = Submission()

@State var confirmationMessage = ""
@State var showingConfirmation = false


var body: some View {
    NavigationView {
        Form {
            Toggle(isOn: $submission.fieldOne ) {
                Text("Field One")
            }

我试图以与添加view.addSubview(myForm)的imageView相同的方式将其添加到UIViewController中,但是却收到消息cannot convert value of type form to expected argument type UIView.

如何在此UIViewController中显示表单?

1 个答案:

答案 0 :(得分:1)

您需要使用UIHostingController,如下所示

func configureViewComponents() {

    view.addSubview(imageView)

    let formController = UIHostingController(rootView: myForm())
    if let form = formController.view {
        form.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(form)
        form.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 0).isActive = true
        form.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        form.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
        form.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true

        self.addChild(formController)
    }
}