SwiftUI preview layout: size that fits does not work

Hey, I want my preview to only have the size of the view and not show the whole iPhone. I have already tried it with this code:

struct TimerCardView: View {
   
    
    var body: some View {
        Text("Hello, World!")
            .padding()
            .background(.gray)
    }
}


struct TimerCardView_Previews: PreviewProvider {
    static var previews: some View {
        TimerCardView()
            .previewLayout(.sizeThatFits)
    }
}

but nothing happened. What am I doing wrong? I appreciate help

Accepted Reply

Same here. I found that you have to switch to the static preview mode to get a sizeThatFits layout. In the default dynamic preview mode, the container is always a whole iPhone.

Replies

Preview layouts in Xcode 14 render the layout in live mode by default.

To see the layout with .sizeThatFits select the Selectable option in the bottom left.

I've highlighted it in the image.

"sizeThatFits" means "Fit the container to the size of the preview when offered the size of the device that the preview is running on".

Same here. I found that you have to switch to the static preview mode to get a sizeThatFits layout. In the default dynamic preview mode, the container is always a whole iPhone.

It would be useful if sizeThatFits would drive the selectable mode in preview (as it was working in previous Xcode versions). It is now very annoying to have previews always start in live mode, with bezels. Our screens have previews both "as presented" and "full content only" and this makes it hard to distinguish the intent of preview.

Note that if you use the #Preview macro, .sizeThatFits will not work, even if you use the static preview containter.

As a workaround you can switch to:

struct ***_Previews: PreviewProvider {
    static var previews: some View {
    }
}