Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableParagraphStyle ignores NSWritingDirectionNatural, is defaulting to LTR for arabic text

I'm using the NSAttributedString UIKit Additions to draw an attributed string in a UIView. The problem I have is that despite using a value of NSWritingDirectionNatural for the baseWritingDirection property of my paragraph style, text always defaults to left-to-right.

Here's how I form the attributed string (simplified):

NSString *arabic = @"العاصمة الليبية لتأمينها تنفيذا لقرار المؤتمر الوطني العام. يأتي ذلك بعدما أعلن اللواء الليبي المتقاعد خليفة حفتر أنه طلب من المجلس الأعلى للقض الدولة حتى الانتخابات النيابية القادمة";

NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.baseWritingDirection = NSWritingDirectionNatural;
paragraph.lineBreakMode = NSLineBreakByWordWrapping;

NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
attributes[NSParagraphStyleAttributeName] = paragraph;

NSAttributedString *string = [[NSAttributedString alloc] 
                             initWithString:arabic 
                             attributes:attributes];

And here's how I draw the text:

- (void)drawRect:(CGRect)rect {
    [self.attributedText drawWithRect:rect 
                              options:NSStringDrawingUsesLineFragmentOrigin 
                              context:nil];
}

And yet it still flows from left to right:

screenshot

What am I missing?

like image 998
jaredsinclair Avatar asked May 22 '14 15:05

jaredsinclair


2 Answers

I don't believe the writing direction will be automatically set for you using baseWritingDirection unless you switch languages on the device:

"If you specify NSWritingDirectionNaturalDirection, the receiver resolves the writing direction to either NSWritingDirectionLeftToRight or NSWritingDirectionRightToLeft, depending on the direction for the user’s language preference setting."

For some reason the text you have still doesn't seem to work even with arabic selected without adding the language to your supported localizations. This character seemed to work without doing that for me: كتب

Also, it looks like Xcode reverses the characters in hardcoded arabic strings so that may be screwing with some of this copy and paste.

You can use agiletortoises's suggestion or NSLinguisticTagger's Language tag scheme to manually set the language.

like image 177
bjtitus Avatar answered Nov 19 '22 23:11

bjtitus


I can't explain why it does not work the way you have it written, but I've been using a solution to explicitly set the direction based on known RTL languages, which used this as a starting point:

https://stackoverflow.com/a/16309559

like image 4
agiletortoise Avatar answered Nov 20 '22 01:11

agiletortoise