AutoLayout + RTL + UILabel text alignment

前端 未结 9 1065
面向向阳花
面向向阳花 2020-11-28 11:18

I\'m finally getting round to wrestling with Auto Layout and can\'t seem to figure out how to get right-to-left (RTL) support to work the way I\'d expect/want...

I h

9条回答
  •  情歌与酒
    2020-11-28 11:48

    @Aviel answer as a swift UILabel extension

    //MARK: UILabel extension
    extension UILabel {
        func decideTextDirection () {
            let tagScheme = [NSLinguisticTagSchemeLanguage]
            let tagger    = NSLinguisticTagger(tagSchemes: tagScheme, options: 0)
            tagger.string = self.text
            let lang      = tagger.tagAtIndex(0, scheme: NSLinguisticTagSchemeLanguage,
                tokenRange: nil, sentenceRange: nil)
    
            if lang?.rangeOfString("he") != nil ||  lang?.rangeOfString("ar") != nil {
                self.textAlignment = NSTextAlignment.Right
            } else {
                self.textAlignment = NSTextAlignment.Left
            }
        }
    }
    

    How to use it ?

    label.text = "كتابة باللغة العربية" // Assign text
    label.decideTextDirection()          // Decide direction
    

提交回复
热议问题