hadiidbouk
(Hadi Dbouk)
1
Is there a way to exclude the LocalizedStringResources from my #Previews?
I don't want to see the strings in the String Catalog.
1 Like
You can instruct previews to not use localized strings with verbatim:
// Localized
Text("Lorem Ipsum")
Button("Frobnicate) { ... }
// Not localized
Text(verbatim: "Demo")
Button { ... } label: { Text(verbatim: "Frobnicate") }
It's quite a drag, but this is the way to go.
1 Like
hadiidbouk
(Hadi Dbouk)
3
This won’t work in my case I am passing the string in my custom view initializer 
Does your initializer accepts a LocalizedStringKey, as below? Then you'll need to perform some refactoring in order to support verbatim strings:
// The setup that requires refactoring
struct MyView {
let title: LocalizedStringKey
var body: some View {
Text(title)
}
}
#Preview("Localized ⚠️") {
MyView("Lorem Ipsum")
}
A possible refactoring is to let container views provide their own label view, while preserving your initial API by offering a convenience initializer that accepts a LocalizedStringKey. This is a pattern frequently used in SwiftUI, with Button for example, and that's why I recommend it:
// A typical Button-like view
struct MyView<Label: View>: View {
private var label: Label
init(@ViewBuilder label: () -> Label) {
self.label = label()
}
init(_ title: LocalizedStringKey)
where Label == Text
{
self.init { Text(title) }
}
var body: some View {
label
}
}
#Preview("Localized ⚠️") {
MyView("Lorem Ipsum")
}
#Preview("Not Localized 🙂") {
MyView {
Text(verbatim: "Lorem Ipsum")
}
}
Yes, some agility with Swift generics greatly helps designing the versatile SwiftUI views needed by applications.
Oh, and if you don't like the trailing closure, just define the convenience initializer you need, with a verbatim argument. You're free to provide all the APIs you need:
extension MyView {
// Why not?
init(verbatim title: String)
where Label == Text
{
self.init { Text(title) }
}
}
#Preview("Not Localized (2)") {
MyView(verbatim: "Lorem Ipsum")
}