-
-
Save jeksys/b8bee5e94c937edf3990cc69ed051a16 to your computer and use it in GitHub Desktop.
SwiftUI View to UIView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import SwiftUI | |
// SwiftUI | |
struct SomeView: View, HostingViewInitialization { | |
var body: some View { | |
Text("Hello World!") | |
} | |
} | |
// UIKit | |
class RootViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// SwiftUI View -> UIView | |
let uiView = HostingView<SomeView>() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import SwiftUI | |
protocol HostingViewInitialization { | |
init() | |
} | |
class HostingView<T: View & HostingViewInitialization>: UIView { | |
private(set) var hostingController: UIHostingController<T>! | |
var rootView: T { | |
get { hostingController.rootView } | |
set { hostingController.rootView = newValue } | |
} | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
setup() | |
} | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
setup() | |
} | |
} | |
// MARK: - Private | |
private extension HostingView { | |
func setup() { | |
backgroundColor = .clear | |
hostingController = UIHostingController(rootView: T.init()) | |
hostingController.view.backgroundColor = backgroundColor | |
hostingController.view.frame = self.bounds | |
hostingController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
addSubview(hostingController.view) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment