Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Localize Images in SwiftUI
Written by Team Kodeco

Localizing images is a critical part of application development, especially when your application serves an international audience. Images may contain text or symbols that differ from one culture to another. SwiftUI simplifies the process of working with localized images.

Note: If you want to try out this example, you can download an archive containing the images here.

In a typical scenario, you might wish to display a different image in your app depending on localization. Here’s how you can do that:

  1. Open Assets.xcassets in your Xcode project.
  2. Click + and add a new Image Set. To follow along with this example, name it fruit.
  3. With fruits selected, open the Attributes Inspector, then click Localize to display the localization choices. Check the localizations for which you’ll provide a unique image. Here, select all the options. You’ll see an image set with three wells created for each localization.
  4. . To follow this example, add the orange to the 1x well for English, the strawberry for French and the pineapple for Arabic.

Note: If Arabic or French localizations don’t appear as options, you’ll need to add them in your project settings. See the chapter “Create a Localized String in SwiftUI” for instructions.

Here’s what you should see in Xcode:

Localize an Image Set in the asset catalog to control the image that shows for each language.
Localize an Image Set in the asset catalog to control the image that shows for each language.

Now you can use the Image view to display the localized image like this:

struct ContentView: View {
  var body: some View {
    Image("fruit")
      .resizable()
      .scaledToFit()
  }
}

Change the scheme language to Arabic and your preview should look like this:

Localize an image in SwiftUI.
Localize an image in SwiftUI.

Here, you added an image set called fruit to the Assets.xcassets file and localized it. Then, you created a ContentView that displays a localized text and the localized image.

In this way, localizing images in SwiftUI is efficient and straightforward. By providing different versions of an image for different locales, you ensure that your app respects the cultural nuances of its international users.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.