I have a few views in my app that need to be able to display both LTR and RTL content (not at the same time though), and it has to be unrelated to the general app layout direction. Meaning, I want to be able to tell a specific view to flip its layout from LTR to RTL and vice versa, on the fly, without changing the system language.
I researched this quite a bit, but aside of the following two solutions, it seems like it's not possible:
Flip layout on iPhone for RTL languages
How to force "Respect Language Direction" from RTL to LTR and vice versa
The first solution is not relevant in my case. The second solution gave me the idea to just keep two versions for every view, one for RTL and one for LTR, and use the relevant one on the fly. That means I'm going to have to update twice the views on every UI update though.
A third solution, of course, is to manually change the view's layout, programatically, according to the relevant direction, before showing the view.
So, are those my only options?
P.S: I'm talking about the layout only, not the localisation strings, as i'm handling the proper text myself.
As of iOS 9, you are now able to do this on a per-view basis using UIView
's semanticContentAttribute
property. If you are using Auto Layout or if your controls are/inherit from UIKit, they should just do the right thing whenever this property is set.
Do note that for labels, text fields and views, you might also have to change the text alignment depending on the text you are displaying.
I found it's quite easy to implement that, just:
func setRTL(_ sender: UIButton) {
UIView.appearance().semanticContentAttribute = .forceRightToLeft
UINavigationBar.appearance().semanticContentAttribute = .forceRightToLeft
if let vc = storyboard?.instantiateViewController(withIdentifier: "root") {
UIApplication.shared.keyWindow?.rootViewController = vc
}
}
Preview:
And check out the full DEMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With