UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Problems adding SwiftUI to UIKit app: Must do 'viewWillLayoutSubviews' and set contentview.view.frame or it breaks?!

Forums > SwiftUI

Here is what's working:

import UIKit
import Foundation
import SwiftUI

class QuickCalculationsViewController: UIViewController
{
   let contentView = UIHostingController(rootView: QuickCalculationsView(settings: iDSMenuSettingsModel.shared, tabBarModel: VerticalTabBarModel(), calcsViewModel: SubCalculationsViewModel()))

  // MARK: VIEW OVERRIDES
  override func viewDidLoad()
  {
    super.viewDidLoad()

    addChild(contentView)
    contentView.view.frame = view.bounds

    view.addSubview(contentView.view)
  }

  override func viewWillLayoutSubviews()
  {
    super.viewWillLayoutSubviews()

    contentView.view.frame = view.bounds
  }
}

The problem is that I'm having to have the 'contentView' as a property so that I can access it and change it's frame in the 'viewWillLayoutSubviews' function, but that means I can't pass in references to view models created in the UIHostingController constructor

i.e.

tabBarModel, calcsViewModel (and other ones I've trimmed out) would like to be set at the same time inside both the VerticalTabBarModel and SubCalculationsViewModel so they have a reference to each other (and can pass data to each other)

The only way to do that is to create those models in the root ViewController atomically, and then pass them into each other, and then use the final versions in the UIHostingController constructor.

But then I don't have access to it for the 'viewWillLayoutSubviews' function.

But if I remove the viewWillLayoutSubviews then the UI doesn't work on rotation and it doesn't even layout correct on first display.

Where am I going wrong?

2      

Fixed it by changing how I create and add the SwiftUI View.

I followed this article and it fixed all the issues:

https://medium.com/@code_cookies/swiftui-embed-swiftui-view-into-the-storyboard-a6fc96e7a0a1

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.