Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextAlignment inverse of .Natural

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!

like image 274
Danny Bravo Avatar asked Aug 27 '15 09:08

Danny Bravo


4 Answers

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
like image 137
Orkhan Alikhanov Avatar answered Oct 24 '22 17:10

Orkhan Alikhanov


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;
like image 25
Oliver Pearmain Avatar answered Oct 24 '22 18:10

Oliver Pearmain


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!
like image 42
Amin Negm-Awad Avatar answered Oct 24 '22 17:10

Amin Negm-Awad


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.

like image 30
Rob Glassey Avatar answered Oct 24 '22 18:10

Rob Glassey