'Single directional (Height only) self sizing UI components preview
I have a UITableViewCell containing a simple UIStackView and 2 UILabels (So it is from UIKit, NOT native SwiftUI) that should have a static width and dynamic height. How can I have a preview for this without need to see the actual phone size?
Note 1: .sizeThatFits will put all the weight on the width and there will be no multiline labels
Note 2: .device is showing extra useless empty spaces of the main view of the screen.
Note 3: .fixed(width:height:) is not prefered, because it will have less space or extra useless space as our needs.
Note 4: Need something like this: (For UIStackView)

DEMO
struct UILabelPorted: UIViewRepresentable {
var configuration = { (view: UILabel) in }
func makeUIView(context: UIViewRepresentableContext<Self>) -> UILabel {
let uiView = UIViewType()
uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
uiView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
return uiView
}
func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<Self>) { configuration(uiView) }
}
struct UILabel_Previews: PreviewProvider {
static var previews: some View {
UILabelPorted {
$0.text = "This label should have multiple lines like it is in a UITableView cell."
}
.previewLayout(.sizeThatFits)
}
}
Solution 1:[1]
It is not very clear where is the problem, but you need something like
ContentView()
.previewLayout(.fixed(width: 414, height: 300))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asperi |


