A lighter way of discovering text writing direction

后端 未结 3 1208
南方客
南方客 2020-12-09 22:59

I want to determine the writing direction of a string so that I can render Right-to-Left languages such as Arabic correctly in a CALayer.

so I have this method

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 23:19

    Swift

    For me the .natural textAlignment of UITextView did not work unless I edited the text and line from start.

    Based on the great answer to this question and the comment below it.

    let text = "..."
    let lang = CFStringTokenizerCopyBestStringLanguage(text as CFString, CFRange(location: 0, length: text.characters.count))
    
    if let lang = lang {
        let direction = NSLocale.characterDirection(forLanguage: lang as String)
    
        if direction == .rightToLeft {
            textView.textAlignment = .right
        }
        else {
            textView.textAlignment = .left
        }
    }
    

提交回复
热议问题