I couldn't decide whether to post this question here or in SwiftUI Q&A as there's a lot of overlaps.
We're trying to create something similar to UIViewRepresentable for UIKit. This might not work for complicated cases where the View has many pieces but as long as it works for simple cases, we're happy.
The only problem right now is figuring out the correct height. Currently, the height anchor is assigned to CGFloat.greatestFiniteMagnitude, which works but when inspecting the layout in View Hierarchy, it appears the wrapped view is getting stretched all the way down. Also, sometimes View Hierarchy isn't able to draw the wrapped View and I'm unsure if it's a problem of View Hierarchy or our implementation.
final public class SwiftUIConfigurationContainerView<T: View>: UIView {
private var contentView: UIView?
public override var intrinsicContentSize: CGSize {
contentView?.intrinsicContentSize ?? super.intrinsicContentSize
}
private var preferredContentSize: CGSize?
public init(@ViewBuilder _ content: @escaping () -> T) {
super.init(frame: .zero)
setUpContentView(content)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
return nil
}
private func setUpContentView(_ content: @escaping () -> T) {
let contentView = UIHostingConfiguration { [weak self] in
VStack(spacing: .zero) {
content()
.onGeometryChange(for: CGSize.self, of: \.size) { size in
self?.preferredContentSize = size
self?.invalidateIntrinsicContentSize()
}
.frame(maxWidth: .infinity, alignment: .center)
Spacer(minLength: .zero)
}
}
.minSize(width: .zero, height: .zero)
.margins(.all, .zero)
.makeContentView()
self.contentView = contentView
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentView.leadingAnchor.constraint(equalTo: leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: trailingAnchor),
contentView.topAnchor.constraint(equalTo: topAnchor),
contentView.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude),
])
}
}