Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize UIHostingController to wrap it's SwiftUI View?

I have a basic SwiftUI component.

struct PopupModal: View {
    var body: some View {
        Text("Hello, World!")
    }
}

struct PopupModal_Previews: PreviewProvider {
    static var previews: some View {
        PopupModal()
    }
}

And I have a UIViewController that I want to instantiate this component and show it.

    private let _popup = PopupModal()
    private lazy var _popupController = UIHostingController(rootView: _popup)

    override public func viewDidLoad() {
        // ...
        self.addChild(_popupController)
        view.addSubview(_popupController.view)
        _popupController.didMove(toParent: self)

    }

    override public func viewDidLayoutSubviews() {
        // How do I make this automatic or as a function of the size of _popup?
        let popupHeight = CGFloat(260)
        _popupController.view.frame = CGRect(x: 15, y: view.bounds.height - popupHeight - 20, width: view.bounds.width - 30, height: popupHeight)
    }

The PopupModal is shown, but I'm manually sizing the height of it. How can I size it based off of the size of the content?

like image 512
Aidan Rosswood Avatar asked Mar 13 '20 01:03

Aidan Rosswood


1 Answers

You can use

  _popupController.view.sizeToFit()

to make view initially fit to its intrinsic content and after adding to superview use auto-layout constrains to layout it as required.

like image 196
Asperi Avatar answered Nov 11 '22 19:11

Asperi