NSTextAlignment inverse of .Natural
I do no think that there is a text alignment "unnatural".
But you can retrieve the natural language direction from NSLocale
with +characterDirectionForLanguage:
. Having this, you can set set the alignment yourself.
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!
In Apple's Internationalization and Localization Guide, under Supporting Right-to-Left Languages, they indicate that getting the layout direction should be done using UIView
's semanticContentAttribute
. So you could implement something like the following:
extension UIView {
var isRightToLeftLayout: Bool {
return UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft
}
}
This has the advantage of not relying on things like UIApplication
, which depending on whether you're working in an extension or not (eg the Today widget), you might not have access to.
Thanks you @Oliver, here is what I ended up using in swift:
Extension
extension NSTextAlignment {
static var invNatural: NSTextAlignment {
return UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? .left : .right
}
}
Usage
myLabel.textAlignment = .invNatural
Heaven knows why Apple don't offer a NSTextAlignmentNaturalInverse or equivalent.
Here is the code we use to achieve this in our producation app...
+ (BOOL)isLanguageLayoutDirectionRightToLeft
{
return [UIApplication sharedApplication].userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft;
}
someLabel.textAlignment = [UIApplication isLanguageLayoutDirectionRightToLeft] ? NSTextAlignmentLeft : NSTextAlignmentRight;