I have an issue when trying to convert a custom View that inherits from UIView into a SwiftUI view, the view takes the whole screen. But it works pretty well if I inherit from UILabel instead of UIView.
Note This view is shown inside a UIHostingController
.
class ViewController: UIViewController {
let hostingVC = UIHostingController(rootView: SwiftUIView())
override func viewDidLoad() {
super.viewDidLoad()
addChild(hostingVC)
view.addSubview(hostingVC.view)
hostingVC.didMove(toParent: self)
hostingVC.view.backgroundColor = .red
hostingVC.view.wh_activateConstraints(configuration: {
[
$0.topAnchor.constraint(equalTo: view.topAnchor),
$0.leadingAnchor.constraint(equalTo: view.leadingAnchor),
$0.trailingAnchor.constraint(equalTo: view.trailingAnchor),
$0.bottomAnchor.constraint(equalTo: view.bottomAnchor),
]
})
}
}
Example 1: this will work
struct SwiftUIView: View {
var body: some View {
VStack {
CustomLabel()
.fixedSize(horizontal: false, vertical: true)
}
}
struct CustomLabel: UIViewRepresentable {
func updateUIView(_ uiView: UIViewType, context: Context) {
}
func makeUIView(context: Context) -> some UIView {
let view = UILabel()
view.text = "hello world"
view.backgroundColor = .green
return view
}
}
Example 2: this will not work
struct SwiftUIView: View {
var body: some View {
VStack {
CustomLabel()
.fixedSize(horizontal: false, vertical: true)
}
}
}
struct CustomLabel: UIViewRepresentable {
func updateUIView(_ uiView: UIViewType, context: Context) {
}
func makeUIView(context: Context) -> some UIView {
let view = CustomUIlabel()
view.backgroundColor = .green
return view
}
}
class CustomUIlabel: UIView {
init(){
super.init(frame: .zero)
let label = UILabel(frame: .zero)
label.text = "hello world"
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
NSLayoutConstraint.activate(
[
label.topAnchor.constraint(equalTo: topAnchor),
label.leadingAnchor.constraint(equalTo: leadingAnchor),
label.trailingAnchor.constraint(equalTo: trailingAnchor),
label.bottomAnchor.constraint(equalTo: bottomAnchor)
]
)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
And when adding .fixedSize(horizontal: false, vertical: true)
for second example the custom view will disappear.
and If I comment it, the view will take the whole screen.
Is there any solution to determine the size dynamically of a custom view that inherits from UIView?