我有一个html内容,我想在UILabel上显示。
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes:nil error:nil];
return attrStr;
这适用于英语(LTR语义),但由于我想支持阿拉伯语,因此上述方法保留了属性字符串LTR。
尽管使用此代码:self.view.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;
我已经尝试了
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc]initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
[mutableAttributedString addAttribute:NSWritingDirectionAttributeName value:@[@(NSWritingDirectionRightToLeft | NSWritingDirectionOverride)] range:NSMakeRange(0, string.length)];
return mutableAttributedString;
还是一样。欢迎任何建议。 感谢
答案 0 :(得分:2)
希望对你有用右侧对齐!!
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentRight;
NSDictionary *attr = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
NSError *error = nil;
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc]initWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:attr documentAttributes:nil error:&error];
[attributedText addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, attributedText.length)];
return attributedText;
答案 1 :(得分:0)
问题与文本方向有关,但与对齐有关。奇怪...
最近出现了同样的问题,当来自html的属性字符串的语言方向不正确时。已使用html属性typeListOf = dotNET.System.Type.GetType("System.Collections.Generic.List`1")
objType = dotNET.namespace.SpecificValueClass.zctor().GetType()
paramTypes = dotNET.System.Array.CreateInstance(dotNET.System.Type.GetType("System.Type"), 1)
paramTypes.SetValue(objType, 0)
typeListOfString = typeListOf.MakeGenericType(paramTypes)
newValue = dotNET.namespace.WattPeakValues.zctor()
newValue.ID = 1
settings.SpecificValue.Add(newValue)
修复。
答案 2 :(得分:0)
Swift 版本:
let yourHTMLString = "" // your string
let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)
]
guard let data = yourHTMLString.data(using: .utf8) else { return }
var attributedText: NSMutableAttributedString!
do {
attributedText = try NSMutableAttributedString(data: data, options: options, documentAttributes: nil)
} catch { return }
// This attribute fixes the alignment problem for Arabic language
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .right
attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedText.length))