简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM