iOS 15.0 / macOS 12.0 / tvOS 15.0 / watchOS 8.0
iOS 15 支持 Markdown 字符串。 默认情况下,您可以使用标准的 Markdown 语法来设置字符串样式,例如 **粗体**
和 *斜体*
。 这很不错,但通常需要指定更复杂的样式,例如 字体类型
、 文本颜色
等。
StyledMarkdown 是一个迷你库,允许您在代码中定义自定义样式,并在本地化的 Markdown 字符串中使用这些样式。
SwiftUI
创建 Text
视图,或者为 UIKit
创建 AttributedString
。通过这种方法,您不必每次在 Markdown 中需要自定义样式时都定义一个自定义的 AttributedStringKey
,因为 StyledMarkdown 会为您处理这部分。
let normalStyle = Style { style in
style.font = .subheadline
style.foregroundColor = .red
}
let boldStyle = Style { style in
style.font = Font.italic(.system(size: 20))()
style.foregroundColor = .blue
}
let myStyleGroup = StyleGroup(
base: normalStyle,
[
"bold": boldStyle
]
)
Text(
"Hey ^[buddy](style: 'bold')",
styleGroup: myStyleGroup
)
// or
AttributedString(
localized: "Hey ^[buddy](style: 'bold')",
styleGroup: myStyleGroup
)
StyleGroup 和命名 Style 的想法直接来自 Daniele Margutti
在 GitHub 上的 SwiftRichString
库。 该软件包中也使用了其中的一些代码。
let rainbow: [Color] = [
.blue, .teal, .red, .gray, .yellow, .orange, .purple
]
let rainbowStyleGroup = StyleGroup(
styleCustom: { source in
var attrString = source
for run in attrString.runs {
let currentRange = run.range
var index = currentRange.lowerBound
var colorCounter: Int = 0
while index < currentRange.upperBound {
let nextIndex = attrString.characters.index(
index,
offsetBy: 1
)
attrString[index ..< nextIndex].foregroundColor = rainbow[colorCounter]
colorCounter += 1
if colorCounter >= rainbow.count {
colorCounter = 0
}
index = nextIndex
}
}
return attrString
}
)
Text(
"Rainbow",
styleGroup: rainbowStyleGroup
)
// or
AttributedString(
localized: "Rainbow",
styleGroup: rainbowStyleGroup
)
上面用于彩虹样式的部分代码取自 WWDC'21 的示例应用项目 Caffe,版权 © 2021 Apple Inc.
您可以使用自定义的 link
AttributedStringKey
在字符串中添加链接: ^[styled link](link: {url: 'http://www.example.com', style: 'linkStyle'})
自动语法协议的 inflect
属性与 StyledMarkdown 样式一起使用。
^[2 salad](style: 'italic', inflect: true)
生成带有斜体样式的 2 salads
。
iOS 目前不支持在 AttributedString
中包含自定义的 Image
附件。