AutoLayout + RTL + UILabel text alignment
Asked Answered
C

10

28

I'm finally getting round to wrestling with Auto Layout and can't seem to figure out how to get right-to-left (RTL) support to work the way I'd expect/want...

I have designed the view in Interface Builder as shown:

IB

With the resulting app running as expected when using English:

English

However when switching to an RTL language (Arabic in this case), the entire view flips (which is great) but the UILabel's text is still left aligned. I'd expect it to be right aligned to keep it up against the UIImageView.

Arabic

Clearly I'm missing something and/or this isn't covered by Auto Layout.

Am I supposed to set the textAlignment manually when using an RTL language?

Cawthon answered 11/9, 2013 at 14:48 Comment(12)
I don't think AutoLayout changes internal states of the elements it lays out. In this case, yes - the best bet would be that you need to do this manually.Intine
can you tell me how did you flip the whole view using Auto Layout ?Arezzini
@Arezzini it is done automatically by the system when changing to a language that is right-to-left.Cawthon
@SteveWilford I just use the base storyboard, no additional storyboard for arabic, how does your Xcode know that it should flip the view ? did you design the flipped interface in another Arabic localized storyboard or you just use 1 storyboard for both English & Arabic ?Arezzini
It's all in a single storyboard. I believe Xcode configures it to flip for RTL by default. But make sure you have "Respect language direction" checked on the leading constraint's attributes inspector.Cawthon
How you doing mirroring the UI? If doing apart from changing the language.Please, let me know.Aryanize
It's provided by Auto Layout, when you change the language in the Settings app to an RTL language it will mirror the UI.Cawthon
what was the solution for this?Jereme
@NickGinanto it depends on your specific requirements, if you're happy to have the width of the label based on it's intrinsic content size then DarthMike's answer is the best (and I've actually been tempted to accept that). However if you need the width of the label to remain as shown you'd need to go down the route of NSTextAlignmentNatural as mentioned in both Ken's answer and my own. I haven't tried it on iOS 7+ (I go with intrinsicContentSize).Cawthon
thanks, in IB it seems the only way to set natural alignment is to use attributed stringJereme
Same type of requirement is this mine. How do i do this from autolayoutEncumber
how to achieve using autoresize or without autolayoutIntimate
C
34

You want NSTextAlignmentNatural. That infers the text alignment from the loaded application language (not from the script).

For iOS 9 and later (using Xcode 7), you can set this in the storyboard (choose the --- alignment option). If you need to target earlier releases, you'll need to create an outlet to the label and set the alignment in awakeFromNib.

- (void)awakeFromNib {
    [[self label] setTextAlignment:NSTextAlignmentNatural];
}
Charry answered 11/9, 2013 at 18:37 Comment(6)
This sounds promising. I'll give this a try in the morning.Cawthon
I'm accepting this as it pointed me in the right direction, but it isn't quite this simple. See my answer for details.Cawthon
Xcode 7 allows setting natural alignment on labels.Limacine
A little improvement in the answer: Check for Center-Align text... if (self.textAlignment != NSTextAlignmentCenter) { [self setTextAlignment:NSTextAlignmentNatural]; }Aleuromancy
Rectification: setTextAlignment should be invoked after awakeFromNib (e.g. in viewDidLoad), otherwise, the UILabel properties defined at the storyboard level will be applied (and therefore override whatever you defined...)Acciaccatura
Where you want the text to be center align, it will change that also to right align.Carbamate
L
13

For me those solutions didn't help, and I ended up doing something pretty ugly but it's the only one that did the trick for me. I added it as an NSString category:

NSString+Extras.h:

#import <Foundation/Foundation.h>

@interface NSString (Extras)
- (NSTextAlignment)naturalTextAligment;
@end

NSString+Extras.m:

#import "NSString+Extras.h"

@implementation NSString (Extras)

- (NSTextAlignment)naturalTextAligment {
    NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
    NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
    [tagger setString:self];
    NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
    if ([language rangeOfString:@"he"].location != NSNotFound || [language rangeOfString:@"ar"].location != NSNotFound) {
        return NSTextAlignmentRight;
    } else {
        return NSTextAlignmentLeft;
    }
}
@end

To detect the language I used this SO answer.

Louralourdes answered 10/4, 2014 at 12:28 Comment(3)
"Natural" alignment only works if you are letting the OS load the correct localization for your app based on system-wide user settings and you have ar.lproj or he.lproj in your app. If you have an in-app language picker, natural won't work, and your code is needed.Treenware
Well, @lensovet, "Natural" means the way nature meant. And nature meant for heb/ar to be right-to-left. The system tries to do it with setTextAlignment:NSTextAlignmentNatural but from my experience it doesn't work as it should, and my solution, albeit not "clean", works; it aligns the text in it's natural way, regardless of the system language. What you want is something like "system-lang alignment", which is not "natural alignment".Louralourdes
You're welcome to file a bug report requesting that. All I'm saying is that's how it works today. It's based on the UI language of the app, not the contents of the text.Treenware
C
5

Follow up from Ken's answer

Setting textAlignment to NSTextAlignmentNatural is not possible on UILabel, it will result in an exception getting thrown:

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'textAlignment does not accept NSTextAlignmentNatural'

It does work when using attributed text and this can be set in Interface Builder as shown:

attributed text natural alignment

However, it would appear that attributed text is not picked up when localising the storyboard.

To get around this I have left the UILabel configured as plain in Interface Builder and created an NSAttributedString with the label's text, set the alignment on the attributed string and assign it to the label's attributedText property:

-(void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentNatural;

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.lbl.text];
    [string addAttribute:NSParagraphStyleAttributeName
                   value:paragraphStyle
                   range:NSMakeRange(0, string.length)];

    self.lbl.attributedText = string;
}

This works fine in this simple case but I can see it falling over when you need more complex attributed string styling. But obviously in that case you'd probably just be using NSLocalizedString or equivalents when creating the NSAttributedString.

Cawthon answered 12/9, 2013 at 8:32 Comment(11)
This sounds like a bug. Have you filed one yet? I’d definitely dupe it!Abiding
I haven't filed a bug as it's mentioned in the release notes for 6.1, right at the bottom: developer.apple.com/library/ios/releasenotes/General/…Cawthon
Nice catch! But since it’s a severe limitation, I’d be tempted to call it bug even though enhancement request would be more suiting ;-)Abiding
It no longer crashes in iOS 7, but it doesn't seem to right align RTL text :/Cawthon
@SteveWilford Hence, me visiting this question. I think you have to set the alignment after setting the text. Have you figured it out?Uncourtly
This snippet + defining my UILabel to attributed in my storyboard doesn't seem to work on iOS7 with Hebrew text... Any ideas? (I have made sure the text is available and is correct with hebrew chars only at time of running these lines in my viewWillAppear)Louralourdes
@SteveWilford is this working for you on iOS 8 or iOS 7?Asclepius
Natural alignment is based on the UI language of the app, not the content of the label.Treenware
@lensovet, what does "the UI language of the app" mean?Daedal
I can confirm that this solution by Steve Wilford does not work in iOS 13. For a super simple iOS application which demonstrates this please see here.Daedal
I did some experimentation and figured out that what @Treenware meant by "the UI language of the app" was the "the language of the device". So when the UILabel's text alignment is set to natural and the device's language is set to English then the text in the UILabel will left-align regardless of its content. And when the UILabel's text alignment is set to natural and the device's language is set to Arabic then the text in the UILabel will right-align. For a super simple application which demonstrates this see here.Daedal
V
5

@Aviel answer as a swift UILabel extension

//MARK: UILabel extension
extension UILabel {
    func decideTextDirection () {
        let tagScheme = [NSLinguisticTagSchemeLanguage]
        let tagger    = NSLinguisticTagger(tagSchemes: tagScheme, options: 0)
        tagger.string = self.text
        let lang      = tagger.tagAtIndex(0, scheme: NSLinguisticTagSchemeLanguage,
            tokenRange: nil, sentenceRange: nil)

        if lang?.rangeOfString("he") != nil ||  lang?.rangeOfString("ar") != nil {
            self.textAlignment = NSTextAlignment.Right
        } else {
            self.textAlignment = NSTextAlignment.Left
        }
    }
}

How to use it ?

label.text = "كتابة باللغة العربية" // Assign text
label.decideTextDirection()          // Decide direction
Vociferation answered 8/2, 2016 at 11:55 Comment(1)
its better to base the textAlignment value on (NS)Locale's characterDirection valueBrandebrandea
R
4

I think you don't want to use text alignment in this case, for a label.

You can just let the width be determined by intrinsicContentSize, and remove any width constraints on the label. You will achieve the desired effect of the label text aligned to the view.

For x axis, you only need this constraint between label and imageview: [imageview]-[label]

This is only a horizontal spacing constraint. No leading or trailing to superview.

Radiochemical answered 11/9, 2013 at 16:19 Comment(1)
Well, you'll want to add a ≥ standard trailing constraint to make sure the text doesn't run off the edge of the screen, which can happen with larger fonts/dynamic type/other strings. But yes, that is a legitimate workaround for apps targeting iOS 8 or older.Treenware
H
3

@Aviel answer as a swift 4 UILabel extension

extension UILabel {
    func decideTextDirection () {
        let tagScheme = [NSLinguisticTagScheme.language]
        let tagger    = NSLinguisticTagger(tagSchemes: tagScheme, options: 0)
        tagger.string = self.text
        let lang      = tagger.tag(at: 0, scheme: NSLinguisticTagScheme.language,
                                          tokenRange: nil, sentenceRange: nil)

        if lang?.rawValue.range(of: "he") != nil ||  lang?.rawValue.range(of: "ar") != nil {
            self.textAlignment = NSTextAlignment.right
        } else {
            self.textAlignment = NSTextAlignment.left
        }
    }
}

usage

label.text = "كتابة باللغة العربية" // Assign text
label.decideTextDirection()          // Decide direction
Helpless answered 4/11, 2018 at 9:6 Comment(1)
I would use: tagger.tag(at: 0, unit: .document, scheme: .language, tokenRange: nil)Unlucky
F
1

This function helped me out

-(void)fnForWritingDirection:(UILabel*)label textFor:(NSString *)stringForText{

    NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString: [stringForText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    [paragraphStyle setBaseWritingDirection:NSWritingDirectionRightToLeft];

    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attrStr length])];

    label.attributedText=attrStr;

}
Fryer answered 7/5, 2015 at 8:32 Comment(1)
You should never force the base writing direction of text unless absolutely necessary. In this case, it isn't.Treenware
W
1

this worked for me:

extension UILabel {
    func decideTextDirection () {
        let tagScheme = [NSLinguisticTagScheme.language]
        let tagger = NSLinguisticTagger(tagSchemes: tagScheme, options: 0)
        tagger.string = self.text
        let lang = tagger.tag(at: 0, scheme: NSLinguisticTagScheme.language, tokenRange: nil, sentenceRange: nil)
        let langDir = NSLocale.characterDirection(forLanguage: lang?.rawValue ?? "en")
        if langDir == .rightToLeft { self.textAlignment = NSTextAlignment.right }
        else { self.textAlignment = NSTextAlignment.left }
    }
}

usage:

nameLabel.text = "مهدی"
nameLabel.decideTextDirection()
Webbing answered 25/12, 2021 at 1:8 Comment(0)
P
0

You can use MyLinearLayout to easy support RTL and LRT.

Park answered 16/5, 2017 at 3:2 Comment(1)
There's nothing in the README of the repository which you linked which explains how it makes supporting RTL and LRT easier. Please explain why you linked this repository and how it relates to the original question in this thread.Daedal
G
0

Here is my version. It's simpler and also handles multiple languages in the source document.

The Main point is to use the dominantLanguage:

let lang = tagger.dominantLanguage

Code Snippet:

 extension UILabel {
    func determineTextDirection () {
        guard self.text != nil else {return}

        let tagger = NSLinguisticTagger(tagSchemes: [.language], options: 0)
        tagger.string = self.text

        let lang = tagger.dominantLanguage

        let rtl = lang == "he" || lang == "ar"

        self.textAlignment = rtl ? .right : .left
    }
}

Usage:

titleLabel.text = "UILabel היפוך שפה עבור"
titleLabel.determineTextDirection()

Finally: Note that if the App is localized and you may rely on the phones language - the solution your after is: "Natural Text Alignment for RTL": i.e:

titleLabel.textAlignment = .natural

enter image description here

Use the NSLinguisticTagger when your app shows multiple lines with different languages. or when you allow free search in any language, regardless of the local.

Grippe answered 13/2, 2020 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.