您好,我现在正在做一个项目,我必须在标签中支持rtl文本

我有用swift 3编写的代码段,但是在swift 4和5中不再起作用。我尝试更新它,但是我不清楚如何更新它

extension UILabel {
func decideTextDirection () {
    let tagScheme = [NSLinguisticTagSchemeLanguage]
    let tagger    = NSLinguisticTagger(tagSchemes: tagScheme, options: 0)
    tagger.string = self.text
    let lang      = tagger.tag(at: 0, scheme: NSLinguisticTagSchemeLanguage,
                                      tokenRange: nil, sentenceRange: nil)

    if lang?.range(of:"ar") != nil {
        self.textAlignment = NSTextAlignment.right
    } else {
        self.textAlignment = NSTextAlignment.left
    }
}

在标签上使用以下添加内容:
detailLabel.text = details[0]

detailLabel.decideTextDirection()

最佳答案

我将您的扩展程序放在Playground中,并解决了编译器错误。这是我想出的:

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 let _ = lang?.rawValue.contains("ar") {
            self.textAlignment = NSTextAlignment.right
        } else {
            self.textAlignment = NSTextAlignment.left
        }
    }
}

10-08 03:15