我理解通过使用NSTextAlignment.Natural
你允许标签使用给定语言的默认正确方向绘制它的内容,这有助于堆积本地化,允许标签从英语/西班牙语等语言从左到右绘制文本...,从阿拉伯语等语言中从右到左。现在我的问题是我希望在与.Natural相反的方向上绘制标签,所以从左到右的语言,文本应该对齐右边,从右到左的语言,它应该对齐到左边。
我找不到NSTextAlignment枚举选项。所以我希望有人能就如何做到这一点给我一些建议?
非常感谢!
天知道为什么Apple不提供NSTextAlignmentNaturalInverse或等价物。
以下是我们在生产应用程序中用于实现此目的的代码...
+ (BOOL)isLanguageLayoutDirectionRightToLeft
{
return [UIApplication sharedApplication].userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft;
}
someLabel.textAlignment = [UIApplication isLanguageLayoutDirectionRightToLeft] ? NSTextAlignmentLeft : NSTextAlignmentRight;
谢谢@Oliver,这是我最终在swift中使用的内容:
extension NSTextAlignment {
static var invNatural: NSTextAlignment {
return UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? .left : .right
}
}
myLabel.textAlignment = .invNatural
我不认为文本对齐“不自然”。
但是你可以用NSLocale
从+characterDirectionForLanguage:
中检索自然语言方向。有了这个,你可以自己设置对齐。
NSLocale *locale = [NSLocale currentLocale];
UInt dir = [NSLocale characterDirectionForLanguage:locale.localeIdentifier];
NSLog(@"%d", dir); // returns 1 for left-to-right on my computer (German, de_DE) Hey, that should be ksh_DE!
在Apple的国际化和本地化指南中,在Supporting Right-to-Left Languages下,他们指出应该使用UIView
的semanticContentAttribute
来完成布局方向。所以你可以实现类似以下的东西:
extension UIView {
var isRightToLeftLayout: Bool {
return UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft
}
}
这样做的好处是不依赖于像UIApplication
这样的东西,这取决于你是否在扩展中工作(例如今天的小部件),你可能无法访问。