2

I have a UIViewController that is presenting a via a function in my viewDidLoad:

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

func configureViewComponents() {
    
    view.addSubview(imageView)

Call it as such:

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

I have a form in a separate file form.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")
            }

I am trying to add it to my UIViewController in the same fashion I add my imageView with view.addSubview(myForm) but I am getting the message cannot convert value of type form to expected argument type UIView.

How can I present my form in this UIViewController?

Anthony
  • 929
  • 7
  • 21

1 Answers1

1

You need to use UIHostingController, like below

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)
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690