How to localize images in iOS/Swift [RTL]

Consider you are developing a movie app which is supposed to be released in all over the world. You get a poster image from your marketing team, and you will need to display text on it as shown below. The below image is for left to right language. The text is on the right side.

It’s easy to handle the text using the method call NSLocalizedString("redflower", comment: "This is the name of my website") For arabic or right to left languages, it’s a different ball game. The image should be displayed as shown below.

As you can see the image is flipped, and the text is automatically set to the left side. All of these changes can be done by the OS. Let me show you how this can be done. To change the image layout, all you need to do is

let layoutDirection = UIView.userInterfaceLayoutDirection(for: attribute)
if layoutDirection == .rightToLeft {
  let image = imageView.image?.withHorizontallyFlippedOrientation()
  imageView.image = image

You are basically checking the layout direction and then flipping the image. That will take care of your image. Now moving on to the label. I have used storyboard to layout my label. I will paste the constraints below

Set the leading and trailing constraints and iOS will automatically handle the language changes for you. If you don’t prefer to use storyboard to handle this for you, the constraints can be described as shown below

textLabel = UILabel(frame: storyboardLabel.frame)
textLabel?.textColor = UIColor.white
textLabel?.text = NSLocalizedString("subtitle", comment: "This is the name of my website")
self.view .addSubview(textLabel!)
textLabel?.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 216.0).isActive = true
textLabel?.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
textLabel?.topAnchor.constraint(equalTo: storyboardLabel.bottomAnchor, constant: 5.0).isActive = true
textLabel?.translatesAutoresizingMaskIntoConstraints = false

Lastly, using imageFlippedForRightToLeftLayoutDirection on UIImage will also do the trick for RTL languages.

One more thing, you can change the locale and language using the scheme to test your changes faster.

Leave a Reply

Your email address will not be published. Required fields are marked *