Text SwiftUI:文本视图连接如何使用ForEach循环或字符串数组进行连接
我需要使用Text SwiftUI:文本视图连接如何使用ForEach循环或字符串数组进行连接,text,concatenation,swiftui,Text,Concatenation,Swiftui,我需要使用+操作符连接SwiftUI中的Text()视图 我试过这样的东西 Text("\(feed.author?.firstName ?? "") \(feed.author?.lastName ?? "") ") .font(.custom("AvenirNext-Medium", size: 15)) .foregroundColor(.black) ForEach(fee
+
操作符连接SwiftUI中的Text()
视图
我试过这样的东西
Text("\(feed.author?.firstName ?? "") \(feed.author?.lastName ?? "") ")
.font(.custom("AvenirNext-Medium", size: 15))
.foregroundColor(.black)
ForEach(feed.titleChunks, id: \.self) { chunk in
+ Text("\(chunk)")
.font(.custom("AvenirNext-Regular", size: 15))
.foregroundColor(Color("BodyText"))
}
但它当然不起作用。是否有一种方法可以获得使用文本打印的未知数量元素的字符串数组,从而在SwiftUI中形成单一的文本视图,就像
Text(“1”)+Text(“2”)+Text(“3”)
这个问题有什么解决办法吗。我厌倦了静态方法,它可以工作,但我事先不知道我有多少文本()
ForEach
令人困惑的是,它不是一个循环,而是一个ViewBuilder
您需要的是减少。文件将其描述为:
使用reduce(:)方法从
整个序列的元素。例如,您可以使用此方法
在一组数字上求和或积
在SwiftUI
上下文中,您可以按如下方式使用它:
let words = ["This", "is", "an", "example"]
var body: some View {
words.reduce(Text(""), { $0 + Text($1) + Text(" ")} )
}
我使用方法或其他视图找到了解决方案,并使用var-output:Text
variable组装了文本连接
var output = Text("")
let author = Text("\(feed.author?.firstName ?? "") \(feed.author?.lastName ?? "") ")
.font(.custom("AvenirNext-Medium", size: 15))
.foregroundColor(.black)
output = output + author
for chunk in feed.titleChunks {
let chunkText : Text
if chunk.first == "#" {
chunkText = Text("\(chunk)")
.font(.custom("AvenirNext-DemiBold", size: 15))
.foregroundColor(Color("BodyText"))
} else {
chunkText = Text("\(chunk)")
.font(.custom("AvenirNext-Regular", size: 15))
.foregroundColor(Color("BodyText"))
}
output = output + chunkText
}
return output
var output = Text("")
let author = Text("\(feed.author?.firstName ?? "") \(feed.author?.lastName ?? "") ")
.font(.custom("AvenirNext-Medium", size: 15))
.foregroundColor(.black)
output = output + author
for chunk in feed.titleChunks {
let chunkText : Text
if chunk.first == "#" {
chunkText = Text("\(chunk)")
.font(.custom("AvenirNext-DemiBold", size: 15))
.foregroundColor(Color("BodyText"))
} else {
chunkText = Text("\(chunk)")
.font(.custom("AvenirNext-Regular", size: 15))
.foregroundColor(Color("BodyText"))
}
output = output + chunkText
}
return output