I understand that by using NSTextAlignment.Natural
you allow a label draw it's content using the default righting direction for a given language, which helps heaps with localisation, allowing the label to draw it's text from left-to-right in languages like english/spanish/etc..., and from right-to-left in languages like arabic. Now my question is that I want to have a label draw in the opposite direction to .Natural, so in a left-to-right language the text should align to the right and in right-to-left languages it should align to the left.
I cannot find an NSTextAlignment enumeration option for this. so I was hoping somebody would give me some advice on how to accomplish this?
Many thanks!
Thanks you @Oliver, here is what I ended up using in swift:
extension NSTextAlignment {
static var invNatural: NSTextAlignment {
return UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? .left : .right
}
}
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;
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.
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