且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UILabel将英语和希伯来语混合为文本时的文本对齐方式?

更新时间:2023-02-26 12:31:45

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

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

您可能还需要在将其设置为UILabel之前进行此操作:

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

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