0

我试图使用属性字符串在 UILabel 上加载一个简单的 html 字符串(有一个表),如果语言是英语,它适用于 rtl 布局格式不起作用,但它适用于 WKWebView,这里是样本

    let testStr = "<html dir = \"RTL\"> <table border=\"1\"  width = 
    \"514.0\" ><tr><td>عمود 1</td><td>عمود 2</td><td>عمود 3</td><td>عمود 
    4</td><td>عمود 5</td></tr><tr><td>صف 1</td><td><br></td><td><br></td> . 
   <td><br></td><td><br></td></tr><tr><td>صف 2</td><td><br></td><td><br> . 
   </td><td><br></td><td><br></td></tr></table></html>"


testLbl.attributedText =
        testStr.toHtmlAttributedText()


extension String{
    func toHtmlAttributedText() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf8,
                                   allowLossyConversion: true) else { return nil }
        let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
            NSAttributedString.DocumentReadingOptionKey.characterEncoding : String.Encoding.utf8.rawValue,
            NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html,
            
            ]
        let htmlString = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil)
        //this to have borders in html table
        htmlString?.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: NSMakeRange(0, 1))
        return htmlString
    }
}

这是它在模拟器和 html 编辑器上的外观

][1]

][1]

4

1 回答 1

0

尝试使用NSTextAligment

NSTextAligment 为 Text 提供了许多视觉对齐案例。

在您的 UILabel 中,您可以将它们应用为:

label.textAlignment = .natural

.natural -> 表示脚本的默认对齐方式。

提示:探索文档中的 NSTextAligment。NSWritingDirection 是另一个可能对您有更多帮助的枚举。

其次,您还可以处理NSLinguisticTagScheme 以确定输入语言并相应地支持适当的文本对齐方式。

示例代码是:

func helpMeWithDirection(){
 let linguisticTagScheme = [NSLinguisticTagScheme.language]
    let linguicticTagger    = NSLinguisticTagger(tagSchemes: linguisticTagScheme, options: 0)
    linguicticTagger.string = self.text
    let currentLanguage = linguicticTagger.tag(at: 0, scheme: NSLinguisticTagScheme.language,
                                                    tokenRange: nil, sentenceRange: nil)

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

上述函数将是 UILabel 的扩展,因为您正在处理一个。希望这会帮助你。谢谢!

PS:我假设您能够解析属性字符串,并且如图所示,唯一的问题是 rtl

于 2019-08-08T08:28:29.937 回答