Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make my SwiftUI UIViewRepresentable respect intrinsicContentSize in previews?

Tags:

When I create a view in SwiftUI and render it in an Xcode preview, using PreviewLayout.sizeThatFits, the preview adjusts its size according to its content. When I import a UIKIt view using UIViewRepresentable, it appears with a full device-size frame.

Is there a way to make SwiftUI respect the intrinsicContentSize of UIView subclasses?

struct Label: UIViewRepresentable {      func makeUIView(context: UIViewRepresentableContext<Label>) -> UILabel {         return UILabel()     }      func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<Label>) {         uiView.text = "Some text"     } }  #if DEBUG struct Label_Previews: PreviewProvider {     static var previews: some View {         Group {             Label().previewLayout(.sizeThatFits)         }     } } #endif 
like image 860
knellr Avatar asked Jun 19 '19 10:06

knellr


1 Answers

Add the following to your updateUIView function:

uiView.setContentHuggingPriority(.defaultHigh, for: .vertical) uiView.setContentHuggingPriority(.defaultHigh, for: .horizontal) 
like image 97
dwitt Avatar answered Oct 10 '22 02:10

dwitt