当英语和希伯来语混合为文本时,UILabel文本对齐?

时间:2014-06-27 16:06:25

标签: ios uilabel autolayout hebrew

UILabel有一个混合了英语和希伯来语的文本。我希望按照英语LTL和希伯来语RTL的语言方式进行对齐。

文字是

  

上帝保佑你创造葡萄的果实:

     

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

1 个答案:

答案 0 :(得分:3)

以下是您可能受到启发的示例。

注意:我不知道你是如何创建所有文本的,所以我不知道你会怎么知道英语中的内容或希伯来语中的内容,但你会明白这一点。

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];

在将其设置为UILabel

之前,您可能还想这样做
[attrStr addAttribute:NSFontAttributeName
                value:[UIFont whateverFontWithWhateverSize]
                range:NSMakeRange(0, [attrStr length])];