NSTextAlignment is the reverse. Natural

I understand that using NSTextAlignment.Natural , you allow the label to draw its contents using the correct default direction for the given language, which helps heaps with localization by letting the label draw text from left to right in languages ​​like English / Spanish / etc. etc., and from right to left in languages ​​such as Arabic. My question now is that I want the label to draw in the opposite direction. Naturally, therefore, in the left correct language, the text should be aligned from right and from right to left, it should be aligned to the left,

I cannot find the NSTextAlignment enumeration option for this. so I was hoping someone would give me some tips on how to do this?

Many thanks!

+10
ios objective-c uilabel swift
source share
4 answers

Heaven knows why Apple does not offer NSTextAlignmentNaturalInverse or the equivalent.

Here is the code we use to achieve this in our application to create ...

 + (BOOL)isLanguageLayoutDirectionRightToLeft { return [UIApplication sharedApplication].userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft; } someLabel.textAlignment = [UIApplication isLanguageLayoutDirectionRightToLeft] ? NSTextAlignmentLeft : NSTextAlignmentRight; 
+11
source share

Thanks @Oliver, here is what I ended up using in a quick one:

Expansion

 extension NSTextAlignment { static var invNatural: NSTextAlignment { return UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? .left : .right } } 

Using

 myLabel.textAlignment = .invNatural 
+6
source share

I don’t think there is an “unnatural” text alignment.

But you can get the natural language direction from NSLocale with +characterDirectionForLanguage: After that, you can set the setting 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! 
+1
source share

In the Apple Internationalization and Localization Guide, in the " Language Support from Right to Left" section, they indicate that getting the direction of the layout should be done using the UIView semanticContentAttribute . So you can 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 are working on an extension or not (for example, the Today widget), you may not have access to.

0
source share

All Articles