SwiftUI preview layout: size that fits does not work
Asked Answered
M

2

24

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

Maid answered 14/11, 2022 at 8:57 Comment(0)
S
61

In Xcode 14+, the default mode for the Preview canvas is live mode, which as you’re seeing places your preview into a device screen context.

Manually adjusting the preview layout requires “selectable” mode, which was the default in previous versions of Xcode. You can switch between modes using the palette at the bottom of the toolbar canvas. For example:

GIF showing difference between preview modes

Sententious answered 14/11, 2022 at 10:55 Comment(0)
T
41

Xcode 15 you can do it.

#Preview(traits: .sizeThatFitsLayout) {
    ContentView()
}
Thoracotomy answered 24/9, 2023 at 16:34 Comment(3)
And in addition to this, I think you have to also press the "selectable" mode like we see in the @Sententious answer. The Lord Always Delivers!Retro
you need to add @available(iOS 17, *) before #Preview if you support iOS 16 and iOS 17Radiolucent
Interestingly, with Xcode 15.1, the preview is broken as long as you select My Mac in the preview simulation. Any iOS device works.Juan

© 2022 - 2024 — McMap. All rights reserved.