如何通过循环组合文本视图?
How can I combine text views by looping?
我们可以使用 + 从多个小文本视图创建新的文本视图,这是创建更高级格式的简单方法。例如,这将创建三个不同颜色的文本视图并将它们组合在一起:
struct ContentView: View {
var body: some View {
Text("Colored ")
.foregroundColor(.red)
+
Text("SwifUI ")
.foregroundColor(.green)
+
Text("Text")
.foregroundColor(.blue)
}
}
但是如何通过循环创建组合文本视图。例如(不起作用)
View v;
ForEach((1...3), id: \.self) {
v.append(Text("\([=11=])"))
}
您实质上是在尝试从序列 0...3
中获取 Text
类型的表达式。您可以先 map
序列到 Text
对象。如何将一系列对象组合成一个对象? reduce
!
(1...3).map { Text("\([=10=])") }.reduce(Text(""), +)
请注意,Text("")
的作用类似于 +
操作的标识元素。
我们可以使用 + 从多个小文本视图创建新的文本视图,这是创建更高级格式的简单方法。例如,这将创建三个不同颜色的文本视图并将它们组合在一起:
struct ContentView: View {
var body: some View {
Text("Colored ")
.foregroundColor(.red)
+
Text("SwifUI ")
.foregroundColor(.green)
+
Text("Text")
.foregroundColor(.blue)
}
}
但是如何通过循环创建组合文本视图。例如(不起作用)
View v;
ForEach((1...3), id: \.self) {
v.append(Text("\([=11=])"))
}
您实质上是在尝试从序列 0...3
中获取 Text
类型的表达式。您可以先 map
序列到 Text
对象。如何将一系列对象组合成一个对象? reduce
!
(1...3).map { Text("\([=10=])") }.reduce(Text(""), +)
请注意,Text("")
的作用类似于 +
操作的标识元素。