已弃用: 此库是在结果构建器(以前称为函数构建器)尚未正式成为 Swift 语言的一部分时创建的。现在你可以使用 David Roman 的 TextBuilder 库来代替,它使用最新的 Swift API 提供了相同的基础功能和更多功能。
一个 SwiftUI 视图,用于将多个 Text
视图组合成一个单独的 Text
实例。
Text {
Text("This text can be")
if isTrue {
Text("bold,")
.fontWeight(.bold)
Text("monospaced")
.font(.system(.body, design: .monospaced))
Text("or")
}
Text("styled")
.font(.system(.caption))
Text("however")
.italic()
Text("you")
.font(Font.title.smallCaps())
Text("want and")
Text("everything")
.foregroundColor(.green)
.underline()
Text("will be combined 😃.")
}
类似于构建常规视图层次结构的方式,此库为你提供了 Text
视图的额外初始化器,你可以使用它来构建具有不同样式的复杂句子。在文本定义块中,你可以使用常见的代码指令,例如 if
、if else
、switch
和类似的语句来构建复杂的多样式句子。
你可以使用 Text(_ content:)
初始化器从传递的闭包中提供的多个 Text
视图来构建你的句子。
Text {
Text("Example")
Text("sentence").bold()
}
输出
示例 句子
默认情况下,在内容块中声明的所有 Text
元素都将用空格字符分隔。你可以通过提供自己的分隔符文本来更改此行为。
Text(separator: "-") {
Text("joined")
Text("with")
Text("dashes")
}
输出
joined-with-dashes(用破折号连接)
为了获得更多控制,例如额外的样式,将 Text
实例作为分隔符传入。
Text(separator: Text(" ! ").bold()) {
Text("bold")
Text("exclamation")
Text("mark")
}
输出
bold(粗体) ! exclamation(感叹) ! mark(号)
在文本定义块中,你可以使用控制流语句,例如 if
、switch
或 if let
来构建组合的 Text
。
Text {
Text("Hello,")
if let name = yourName {
Text(name).bold()
} else {
Text("what is your name?")
}
}
输出
Hello, Łukasz