Sanoj Kashyap
Sanoj Kashyap

Reputation: 5060

UILabel text alignment when English and Hebrew mixed as text?

I have UILabel which having a text which is mixed of English and Hebrew. I wanted to alignment as per language means for English LTL and for Hebrew RTL.

Text is

I bless You, God, for creating the fruit of the vine:

בָּרוּךְ אַתָּה יְיָ אֱלֹהֵֽינוּ מֶֽלֶךְ הָעוֹלָם, בּוֹרֵא פְּרִי הַגָּֽפֶן.

Upvotes: 2

Views: 827

Answers (1)

Larme
Larme

Reputation: 26066

Here is a sample you could be inspired with.

Note: I don't know how you create your all text, so I don't know how you'll know what's in English or what in Hebrew, but you'll get the idea.

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"I bless You, God, for creating the fruit of the vine:\n בָּרוּךְ אַתָּה יְיָ אֱלֹהֵֽינוּ מֶֽלֶךְ הָעוֹלָם, בּוֹרֵא פְּרִי הַגָּֽפֶן."];

NSMutableParagraphStyle *englishParagraphStyle = [[NSMutableParagraphStyle alloc] init];
[englishParagraphStyle setAlignment:NSTextAlignmentLeft];

NSMutableParagraphStyle *hebrewParagraphStyle = [[NSMutableParagraphStyle alloc] init];
[hebrewParagraphStyle setAlignment:NSTextAlignmentRight];

NSRange englishRange = NSMakeRange(0, [@"I bless You, God, for creating the fruit of the vine:" length]);
NSRange hebrewRange = NSMakeRange([@"I bless You, God, for creating the fruit of the vine:" length],
                                  [[attrStr string] length] - [@"I bless You, God, for creating the fruit of the vine:" length]);

[attrStr addAttribute:NSParagraphStyleAttributeName
                value:englishParagraphStyle
                range:englishRange];
[attrStr addAttribute:NSParagraphStyleAttributeName
                value:hebrewParagraphStyle
                range:hebrewRange];

[myLabel setAttributedText:attrStr];

You also may want to do this before setting it to your UILabel:

[attrStr addAttribute:NSFontAttributeName
                value:[UIFont whateverFontWithWhateverSize]
                range:NSMakeRange(0, [attrStr length])];

Upvotes: 4

Related Questions