AutoLayout + RTL + UILabel text alignment

前端 未结 9 1050
面向向阳花
面向向阳花 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:35

    @Aviel answer as a swift 4 UILabel extension

    extension UILabel {
        func decideTextDirection () {
            let tagScheme = [NSLinguisticTagScheme.language]
            let tagger    = NSLinguisticTagger(tagSchemes: tagScheme, options: 0)
            tagger.string = self.text
            let lang      = tagger.tag(at: 0, scheme: NSLinguisticTagScheme.language,
                                              tokenRange: nil, sentenceRange: nil)
    
            if lang?.rawValue.range(of: "he") != nil ||  lang?.rawValue.range(of: "ar") != nil {
                self.textAlignment = NSTextAlignment.right
            } else {
                self.textAlignment = NSTextAlignment.left
            }
        }
    }
    

    usage

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

提交回复
热议问题