Last active
September 3, 2024 07:15
-
-
Save VAnsimov/3d30fc02780c4d6fcea4ba425084ae2c 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 { | |
var body: some View { | |
Text("Hello World!") | |
} | |
} | |
// UIKit | |
class RootViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// SwiftUI View -> UIView | |
let swiftUIView = SomeView() | |
let uiView = HostingView(rootView: swiftUIView) | |
} | |
} |
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 | |
class HostingView<T: View>: UIView { | |
private(set) var hostingController: UIHostingController<T> | |
var rootView: T { | |
get { hostingController.rootView } | |
set { hostingController.rootView = newValue } | |
} | |
init(rootView: T, frame: CGRect = .zero) { | |
hostingController = UIHostingController(rootView: rootView) | |
super.init(frame: frame) | |
backgroundColor = .clear | |
hostingController.view.backgroundColor = backgroundColor | |
hostingController.view.frame = self.bounds | |
hostingController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
addSubview(hostingController.view) | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment