AutoLayout + RTL + UILabel text alignment

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

    Here is my version. It's simpler and also handles multiple languages in the source document.

    The Main point is to use the dominantLanguage:

    let lang = tagger.dominantLanguage
    

    Code Snippet:

     extension UILabel {
        func determineTextDirection () {
            guard self.text != nil else {return}
    
            let tagger = NSLinguisticTagger(tagSchemes: [.language], options: 0)
            tagger.string = self.text
    
            let lang = tagger.dominantLanguage
    
            let rtl = lang == "he" || lang == "ar"
    
            self.textAlignment = rtl ? .right : .left
        }
    }
    

    Usage:

    titleLabel.text = "UILabel היפוך שפה עבור"
    titleLabel.determineTextDirection()
    

    Finally: Note that if the App is localized and you may rely on the phones language - the solution your after is: "Natural Text Alignment for RTL": i.e:

    titleLabel.textAlignment = .natural
    

    Use the NSLinguisticTagger when your app shows multiple lines with different languages. or when you allow free search in any language, regardless of the local.

提交回复
热议问题