Maysam Maysam - 5 months ago 48
Swift Question

Detect text direction based on content

I wonder if is it possible to set

UITextView
's text direction dynamically and based on its content?

Default behavior is like this: if you start a line with an LTR language that line will be LTR, but if you begin the next line with an RTL language that line's direction changes to RTL.

enter image description here

What I want is set entire paragraphs direction based on first one.

Is it possible?

Answer

I've had this problem myself. With a little bit of search, made this extension for UITextView which detects the first letter's language and makes it RTL if it's needed. You need to call the function after setting text, so you may want to call it in UITextViewDelegate text change" method.

extension UITextView {
func detectRightToLeft() {
    if let text = self.text where !text.isEmpty {
        let tagschemes = NSArray(objects: NSLinguisticTagSchemeLanguage)
        let tagger = NSLinguisticTagger(tagSchemes: tagschemes as! [String], options: 0)
        tagger.string = text

        let language = tagger.tagAtIndex(0, scheme: NSLinguisticTagSchemeLanguage, tokenRange: nil, sentenceRange: nil)
        if language?.rangeOfString("he") != nil || language?.rangeOfString("ar") != nil || language?.rangeOfString("fa") != nil {
            self.text = text.stringByReplacingOccurrencesOfString("\n", withString: "\n")
            self.textAlignment = .Right
            self.makeTextWritingDirectionRightToLeft(nil)
        }else{
            self.textAlignment = .Left
            self.makeTextWritingDirectionLeftToRight(nil)
        }
    }
}
}

Surely this is messy and not perfect. But it worked for me. You can get the idea.