How can I show two or more different variants in Xcode using the new #Preview macro?
Without the macro, this was possible:
struct TutorialView_Previews: PreviewProvider {
static var previews: some View {
MyAwesomeView(title: "Title One", hideSomePart: true)
.previewDisplayName("Hidden some part")
MyAwesomeView(title: "Title Two", hideSomePart: false)
.previewDisplayName("Showing all parts")
}
}
But with the new macro, this isn't compiling:
#Preview {
MyAwesomeView(title: "Title One", hideSomePart: true)
.previewDisplayName("Hidden some part")
MyAwesomeView(title: "Title Two", hideSomePart: false)
.previewDisplayName("Showing all parts")
}
asked Oct 20, 2023 at 13:40
Jorn Rigter
1,3151 gold badge15 silver badges35 bronze badges
3 Answers 3
Using .previewDisplayName("...") does not work for me. I got it working doing it like this:
#Preview("Hidden some part") {
MyAwesomeView(title: "Title One", hideSomePart: true)
}
#Preview("Showing all parts") {
MyAwesomeView(title: "Title Two", hideSomePart: false)
}
answered Mar 1, 2024 at 12:02
D'Fontalland
4054 silver badges10 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Jorn Rigter
See previewDisplayName documentation -- should work on iOS 13.0+
D'Fontalland
It should but I didn't. They way I got it working was as I showed on my example.
Turned out to be a simple fix:
#Preview {
MyAwesomeView(title: "Title One", hideSomePart: true)
.previewDisplayName("Hidden some part")
}
#Preview {
MyAwesomeView(title: "Title Two", hideSomePart: false)
.previewDisplayName("Showing all parts")
}
answered Oct 20, 2023 at 14:01
Jorn Rigter
1,3151 gold badge15 silver badges35 bronze badges
3 Comments
kakaiikaka
previewDisplayName not work on Xcode 15, Use #Preview("PreviewName") like D'Fontalland said.
Jorn Rigter
Thanks for the heads up! I've accepted their answer as the accepted answer, then it seems like the documentation is wrong about how to show the preview display name
kakaiikaka
they only work if you are not using the new Preview Marco syntax.
Yea if you try using .previewDisplayName in a #Preview macros nowadays it shows a warning - 1. PreviewDisplayName is ignored in a #Preview macro. Provide the name to the macro initializer, e.g. #Preview("preview name")
You should just use "#Preview("your preview name")"
Comments
default