xcode ios 7 - 强制视图布局翻转到 RTL 而无需更改语言
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27685775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ios 7 - Force view layout flip to RTL without language change
提问by Darkshore Grouper
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.
我的应用程序中有一些视图需要能够同时显示 LTR 和 RTL 内容(尽管不是同时显示),并且它必须与一般应用程序布局方向无关。意思是,我希望能够在不更改系统语言的情况下,即时告诉特定视图将其布局从 LTR 翻转到 RTL,反之亦然。
我对此进行了大量研究,但除了以下两种解决方案外,似乎不可能:
在 iPhone 上为 RTL 语言翻转布局
如何强制“尊重语言方向”从 RTL 到 LTR,反之亦然
第一个解决方案与我的情况无关。第二种解决方案让我想到只为每个视图保留两个版本,一个用于 RTL,一个用于 LTR,并即时使用相关的一个。这意味着我将不得不在每次 UI 更新时更新两次视图。
当然,第三种解决方案是在显示视图之前根据相关方向以编程方式手动更改视图的布局。
那么,这些是我唯一的选择吗?
PS:我只是在谈论布局,而不是本地化字符串,因为我自己正在处理正确的文本。
回答by Sayakiss
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.
并查看完整的DEMO。
回答by wakachamo
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.
从 iOS 9 开始,您现在可以使用UIView
'ssemanticContentAttribute
属性在每个视图的基础上执行此操作。如果您使用的是自动布局,或者您的控件是/继承自 UIKit,则只要设置了此属性,它们就应该做正确的事情。
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.
请注意,对于标签、文本字段和视图,您可能还必须根据显示的文本更改文本对齐方式。