Last active
December 27, 2024 16:56
-
-
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 uiKitView = HostingView(rootView: swiftUIView) | |
view.addSubview(uiKitView) | |
// Without this, there may be problems with safeArea in SwiftUI View | |
uiKitView.addChildControllerTo(self) | |
} | |
} |
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
/// HostingView allows you to use SwiftUI View in UIKit code | |
/// | |
/// Warning: | |
/// iPhone models without SafeArea may experience extra ridges. | |
/// There are two ways to solve the problem: either call | |
/// the HostinView method hostingView.addChildControllerTo(self) | |
/// or use the .ignoresSafeArea() method in SwiftUI View. | |
public final class HostingView<T: View>: UIView { | |
private(set) var hostingController: UIHostingController<T> | |
public var rootView: T { | |
get { hostingController.rootView } | |
set { hostingController.rootView = newValue } | |
} | |
public 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) | |
} | |
public required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
public func addChildControllerTo(_ controller: UIViewController) { | |
controller.addChild(hostingController) | |
hostingController.didMove(toParent: controller) | |
} | |
public func removeChildControllerTo(_ controller: UIViewController) { | |
hostingController.willMove(toParent: nil) | |
hostingController.removeFromParent() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This solution has performed well over time, I'm supplemented it with nuances I've discovered.