iOS RTL - improperly displaying English inside RTL string
Asked Answered
C

5

10

iOS application, we're to display news, coming from server. UIlabel is used

  • Everything is perfect when he sentence is in a single language only with no regard to layout (we're switching layout RTL to LTR for different languages, including Arabic, Hebrew)
  • When inside LTR language we have RTL words, they break the sentence structure (see the picture, BTN must be in the beginning of the line, but it jumped to the end) English words inside RTL language Any idea how to solve this? Thanks in advance :)
Control answered 28/5, 2016 at 9:59 Comment(0)
V
17

Apple are using "Unicode Bidirectional Algorithm" to present text. If the first character in a string is LTR the algorithm treat the presentation of the rest of the string as LTR. If you know in advance the language of the string RTL you can use the unicode \u200F and \u202c to force the RTL alignment.

Objective-C

[NSString stringWithFormat:@"\u200F%@\u202c", @"your string with RTL content"]

[NSString stringWithFormat:@"\u200E%@\u202c", @"your string with LTR content"]

Swift

String(format: "\u200F%@\u202c", "your string with RTL content")

String(format: "\u200E%@\u202c", "your string with LTR content")
Verso answered 14/2, 2018 at 13:41 Comment(1)
This seemed to work for me, the relevant documentation from Apple around this can be found here: developer.apple.com/library/archive/documentation/MacOSX/…Subinfeudation
I
5

Here is @Pichirichi solution for swift 5.2 :

"\u{200F}\("your string with RTL content")\u{202c}"

"u200E\("your string with LTR content")\u{202c}"
Inboard answered 18/4, 2020 at 8:12 Comment(0)
I
4

Swift 5:

extension String {
    
    func forceUnicodeRTL() -> String {
        return "\u{200F}\(self)\u{200E}"
    }
}
Implicate answered 19/6, 2021 at 7:6 Comment(0)
C
2
  "arabic text \u200E english text \u200F arabic text \u200E english text"

Solved the issue

Control answered 28/5, 2016 at 14:59 Comment(1)
it didnt work for me. My string is like this self.testLabel.text = @"رقم HELLO سجل";Santos
C
0

Some info from here is helpful:

[[self label] setTextAlignment:NSTextAlignmentNatural];

AutoLayout + RTL + UILabel text alignment

But sometimes it still not working as expected

Control answered 28/5, 2016 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.