Last active
March 14, 2024 10:14
-
-
Save pookjw/78ce2ff52905105a1796d53b90d55a41 to your computer and use it in GitHub Desktop.
UIHostingConfiguration for iOS 14 & 15
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 | |
struct BPHostingConfiguration<Content: View>: UIContentConfiguration { | |
fileprivate let content: Content | |
init(@ViewBuilder content: () -> Content) { | |
self.content = content() | |
} | |
func makeContentView() -> any UIView & UIContentView { | |
HostingView<Content>(configuration: self) | |
} | |
func updated(for state: any UIConfigurationState) -> BPHostingConfiguration { | |
return self | |
} | |
} | |
fileprivate final class HostingView<Content: View>: UIView, UIContentView { | |
private let hostingController: UIHostingController<Content> | |
private var _configuration: BPHostingConfiguration<Content> | |
var configuration: any UIContentConfiguration { | |
@storageRestrictions(initializes: _configuration, hostingController) | |
init(newValue) { | |
let configuration: BPHostingConfiguration<Content> = newValue as! BPHostingConfiguration<Content> | |
_configuration = configuration as! BPHostingConfiguration | |
hostingController = .init(rootView: configuration.content) | |
} | |
get { | |
_configuration | |
} | |
set { | |
let configuration: BPHostingConfiguration<Content> = newValue as! BPHostingConfiguration<Content> | |
_configuration = configuration | |
hostingController.rootView = configuration.content | |
} | |
} | |
init(configuration: any UIContentConfiguration) { | |
self.configuration = configuration | |
super.init(frame: .null) | |
let hostingView: UIView = hostingController.view | |
hostingView.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
addSubview(hostingView) | |
} | |
@available(*, unavailable) | |
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
Example