我需要使用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"))
}
但是它当然不起作用。有没有一种方法可以获取使用Text打印的元素数量未知的字符串数组,以便像
一样在SwiftUI中形成单个文本视图 Text("1") + Text("2") + Text("3")
是吗?
是否有解决此问题的方法。我厌倦了静态方法,并且可以使用,但是我事先不知道我有多少Text()
Text("\(feed.author?.firstName ?? "") \(feed.author?.lastName ?? "") ")
.font(.custom("AvenirNext-Medium", size: 15))
.foregroundColor(.black)
+ Text("\(feed.titleChunks[0])")
.font(.custom("AvenirNext-Regular", size: 15))
.foregroundColor(Color("BodyText"))
+ Text("\(feed.titleChunks[1])")
.font(.custom("AvenirNext-DemiBold", size: 15))
.foregroundColor(Color("BodyText"))
答案 0 :(得分:6)
ForEach
令人困惑的不是循环而是ViewBuilder
您需要的是reduce
。文档将其描述为:
使用reduce(: :)方法从 整个序列的元素。例如,您可以使用此方法 在一组数字上查找其和或积。
在SwiftUI
上下文中,您可以按以下方式使用它:
let words = ["This", "is", "an", "example"]
var body: some View {
words.reduce(Text(""), { $0 + Text($1) + Text(" ")} )
}
答案 1 :(得分:1)
我找到了使用方法或其他视图的解决方案,并使用var output : Text
变量
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