Question
Is there a definitive way to detect if the text direction in NSString
or NSAttributedString
is right-to-left? Text is received from external resource, not entered in the app (can't use UITextInput
protocol methods).
Bad solution
I have been detecting it using CFStringTokenizerCopyBestStringLanguage()
and then +[NSLocale characterDirectionForLanguage:]
, but it is pretty unreliable for strings, where there are only a few arabic characters and many latin. They are processes as a RTL when displayed in the label, but incorrect direction detection makes inconsistent behaviour.
Investigation
During development, I have found out that when creating NSAttributedString
with no attributes except for the font and displaying it using TTTAttributedLabel
, RTL text aligns to the right edge. When using simple NSString
, or when using standard UILabel
with attributed string, alignment stays left.
So, there has to be something in the text that says "it is RTL" and there is some method to detect it.
I analysed what I am receiving from server, and there were no standard Unicode bidi chars. This is how it looks. JSON is sent in ascii with all unicode characters escaped:
"\u0643\u062a\u0628\u062a \u0648\u0648\u062c\u0650 .."
When unescaping, it looks like this, with \u0643
is on the far right before the dots:
"كتبت ووجِ .."
As far as I can tell, every character represents a single character in arabic language, and there are no U+202B
or similar control characters which could be used to easily detect direction.
Yet, when rendering this text through TTTAttributedLabel
, it aligns right. I started looking into the source code, and it doesn't do anything to detect the direction or set the alignment. It only created the framesetter using CTFramesetterCreateWithAttributedString()
and then, when it gets lines from it using CTFrameGetLines()
and line positions with CTFrameGetLineOrigins()
, they are already aligned to the right.
So, does anyone know if direction can be detected solely from the text with publicly available (and preferably fast) API methods?