以@Verglas 的回答为基础...
您通常在 HTML 中执行此类操作的方式是通过浮动。 像这样的东西::
<div><p style='float: left;'>Left</p><p style='float: right;'>Right</p><div style='clear: both;'></div></div>
如果您可以将其转换为 NSAttributedString 并使其工作,那就太好了:
NSString* html = @"<div><p style='float: left;'>Left</p><p style='float: right;'>Right</p><div style='clear: both;'></div></div>";
NSData* d = [html dataUsingEncoding: NSUTF8StringEncoding];
NSAttributedString* as = [[NSMutableAttributedString alloc] initWithData: d
options: @{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)
}
documentAttributes: nil
error: nil];
可悲的是,它不起作用。
对于第二次尝试,我们可以尝试使用 HTML 表格:
html = @"<table style='width:100%'><tr><td>Left</td><td style='text-align:right;'>Right</td></tr></table>";
奇怪的是,这按预期工作。更令人好奇的是它生成的属性:
2014-08-27 14:27:31.443 testParagraphStyles[2095:60b] range: {0, 5} attributes: {
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n \"<NSTextTableBlock: 0x8d9c920>\"\n), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
2014-08-27 14:27:31.444 testParagraphStyles[2095:60b] range: {5, 6} attributes: {
NSParagraphStyle = "Alignment 2, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n \"<NSTextTableBlock: 0x8da1550>\"\n), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
}
向右滚动并注意对 NSTextTableBlock 的引用。NSTextTable 不是 iOS 上的公共 API,但 NSAttributedString initWithData:options:documentAttributes:error: 使用它从 HTML 生成我们的属性字符串。这很痛苦,因为这意味着我们不能手动构造一个 NSAttributedString(我们必须使用这个 API 从 HTML 生成它)。
从 HTML 构建属性字符串很慢,而且很大程度上没有文档记录。我尽可能避免它。