In SwiftUI, how to use UIHostingController inside an UIView or as an UIView?

后端 未结 2 2027
-上瘾入骨i
-上瘾入骨i 2020-12-24 14:17

An alternative question title could be \"How to add an UIHostingController\'s view as subview for an UIView?\".

I am creating a new piece of UI comp

2条回答
  •  一整个雨季
    2020-12-24 14:32

    I have some idea in mind.

    1. Wrap the SwiftUI with a UIHostingController
    2. Initialize the controller
    3. Add the new controller as a child view controller
    4. Add the controller view as a subview to where it should go

    Thus:

    addChild(hostingViewController)
    hostingViewController.view.frame = ...
    view.addSubview(hostingViewController.view)
    hostingViewController.didMove(toParent: self)
    

    A view controller always uses other view controllers as views.

    Stanford CS193P, https://youtu.be/w7a79cx3UaY?t=679

    Reference

    • How to add an UIViewController's view as subview
    • Place UIViewController inside UIView
    • Use UIViewController as TableView cell

提交回复
热议问题