3

I started trying out SwiftUI preview for UIKit views, (by using UIViewRepresentable) and encountered a tricky issue with this setup. I tried to preview the wrapped view in a different Locale using the environment modifier but it just doesn’t work.

Here is a code snippet of the preview:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            SimpleLabelViewWrapper()
                .previewLayout(.fixed(width: 120, height: 50))
                .environment(\.locale, .init(identifier: "fr"))
                .previewDisplayName("UIKit")
            SimpleSwiftUIText()
                .previewLayout(.sizeThatFits)
                .padding()
                .environment(\.locale, .init(identifier: "fr"))
                .previewDisplayName("SwiftUI")
        }

    }
}
  • SimpleLabelViewWrapper conforms to UIViewRepresentable and returns a UIView with a UILabel as a subview.
  • SimpleSwiftUIText is simply a SwiftUI View with Text as a body.

The output preview looks like this: Preview screenshot

Findings

Text has an initialiser:

init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)

The LocalizedStringKey is used to map the value to the localisation table. However, this is not probably used when you simply wrap a UIKit view to SwiftUI as I suspect UIKit views still uses UILabel.textor UILabel.attributedText (i.e. UILabel doesn’t get mapped to Text) to display a string that is not of LocalizedStringKey type hence it defaults to the base language.

This might be a limitation when not using pure SwiftUI but it would be better to fully understand why it doesn't work or if there is a workaround.

0 Answers0