Xcode 15: SwiftUI preview layout: size that fits does not work – Swiftui

by
Alexei Petrov
preview swiftui-ontapgesture xcode15

Quick Fix: To use sizeThatFits layout in SwiftUI previews in Xcode 15, add #Preview(traits: .sizeThatFitsLayout) to the macro declaration.

The Problem:

In Xcode 15, SwiftUI preview layout .sizeThatFits is not working for .fixed size which worked well in Xcode 14 version.

The Solutions:

Solution 1: Utilize Traits in `#Preview` Macro

In Xcode 15, the approach for previewing SwiftUI views has undergone a slight modification. Instead of appending modifiers like .sizeThatFits or .fixed to the view within the #Preview macro, you should now leverage traits. Traits offer a more structured and centralized method for customizing the preview layout.

To preview a view with a size that fits, use the #Preview(traits:) macro and provide .sizeThatFitsLayout as the trait, as seen below:

#Preview(traits: .sizeThatFitsLayout) {
    ContentView()
}

This will allow the view to dynamically adjust its size based on its content, ensuring that it fits appropriately within the preview canvas.

For a fixed-size preview, you can utilize the #Preview(traits:) macro with the .fixedLayout trait, specifying the desired width and height:

#Preview(traits: .fixedLayout(width: 100, height: 100)) {
    ContentView()
}

By incorporating these traits into the #Preview macro, you can achieve precise control over the layout of your SwiftUI previews in Xcode 15.

Q&A

Old method not working in Xcode 15 preview

Use #Preview(traits with modifier rather than modifier on view

What to pass for fixed size preview

Use fixedLayout in #Preview(traits then pass width, height

Video Explanation:

The following video, titled "Mastering Xcode 14 SwiftUI Previews - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this video I hope to share with you some things that you may not know or have forgotten about SwiftUI previews and what changed in Xcode ...