iOS动态类型使用RTF创建NSAttributedString

3
我的应用程序有一个简单的内置帮助页面。该页面从富文本文件中加载到 NSAttributedString 中,并在 UITextView 中显示字符串。
下面是来自 prepareForSegue: 的代码片段,我在使用它进行显示之前加载了 NSAttributedString...
NSURL *const textURL =
[[NSBundle mainBundle] URLForResource: @"DontPanic"
                        withExtension: @"rtf"];

NSDictionary *const options =
@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType};

NSAttributedString *const text =
[[NSAttributedString alloc] initWithURL: textURL
                                options: options
                     documentAttributes: nil
                                  error: nil];

这一切都很好。但是,它不支持iOS的"动态类型" - 字体被烘焙到RTF文件中,并且不会对用户的设置做出反应。
我希望该指南使用系统定义的正文样式:UIFontTextStyleBody和标题:UIFontTextStyleHeadline
我该如何做到这一点?
如果可以避免添加外部库,则可以将指南定义为另一种格式,例如HTML或Markdown。
1个回答

3
你可以通过CSS使用首选字体。例如,你可以创建如下的HTML文档:
<html>
    <body>
        <h1 style="font: -apple-system-headine; font-family:-apple-system;">My heading</h1>
        <p style ="font: -apple-system-body; font-family:-apple-system;">The body of this document</p>
    </body>
</html>

请将上方代码中的NSRTFTextDocumentType替换为NSHTMLTextDocumentType

CSS中首选字体名称的完整列表如下:

-apple-system-headline
-apple-system-subheadline
-apple-system-short-headline
-apple-system-short-subheadline
-apple-system-body
-apple-system-short-body
-apple-system-tall-body
-apple-system-caption1
-apple-system-caption2
-apple-system-short-caption1
-apple-system-footnote
-apple-system-short-footnote

如果您不想在每个元素上定义字体,您可以像这样在html的<head>标签中修改样式:

<html>
  <head>
    <style type="text/css">
      H1 {font: -apple-system-headine; font-family: -apple-system;}
      P {font: -apple-system-body; font-family: -apple-system;}
    </style>
  </head>

  <body>
    <h1>This is a heading. It will be shown with the dynamic type headline font.</h1>
    <p>This is a paragraph. It will use the dynamic type body font.</p>
  </body>
</html>

太棒了,听起来非常有前途。我将非常高兴地停止使用 RTF——使用 HTML 可以更容易地在正确位置插入空白行! - Benjohn
有没有办法可以设置这些字体用于整个文档中的<h1><p>,而不需要每次都引用它们? - Benjohn
啊 - 这可以通过在<head>中设置 <style> 来完成。我将添加一个编辑到你的答案中,展示如何做到这一点。它可能会被拒绝审核 - 如果你认为这是一个好的编辑,请你接受它?非常感谢。 - Benjohn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接