SwiftUI:文本视图连接如何使用 ForEach 循环或字符串数​​组执行此操作

Mic*_*bro 1 text concatenation swiftui

我需要Text()使用+运算符连接SwiftUI 中的视图

我试过这样的事情

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"))
                }
Run Code Online (Sandbox Code Playgroud)

但它当然不起作用。有没有办法获取使用 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"))
Run Code Online (Sandbox Code Playgroud)

LuL*_*aGa 9

ForEach 相当令人困惑的是不是一个循环而是一个 ViewBuilder

你需要的是reduce。文档将其描述为:

使用 reduce( : :) 方法从整个序列的元素生成单个值。例如,您可以在一组数字上使用此方法来查找它们的总和或乘积。

SwiftUI上下文中,您可以按如下方式使用它:

let words = ["This", "is", "an", "example"]

var body: some View {
    words.reduce(Text(""), { $0 + Text($1) + Text(" ")} )
}
Run Code Online (Sandbox Code Playgroud)