我有这个视图可以在多行上显示文本标签,这些文本标签是从带有 Wrap 的 SwiftUI HStack 获得的,但是当我将它添加到 VStack 中时,标签会与我放在下面的任何其他视图重叠。标签显示正确,但视图本身的高度不在 VStack 内计算。如何让这个视图使用内容的高度?
import SwiftUI
struct TestWrappedLayout: View {
@State var platforms = ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"]
var body: some View {
GeometryReader { geometry in
self.generateContent(in: geometry)
}
}
private func generateContent(in g: GeometryProxy) -> some View {
var width = CGFloat.zero
var height = CGFloat.zero
return ZStack(alignment: .topLeading) {
ForEach(self.platforms, id: \.self) { platform in
self.item(for: platform)
.padding([.horizontal, .vertical], 4)
.alignmentGuide(.leading, computeValue: { d in
if (abs(width - d.width) > g.size.width)
{
width = 0
height -= d.height
}
let result = width
if platform == self.platforms.last! {
width = 0 //last item
} else {
width -= d.width
}
return result
})
.alignmentGuide(.top, computeValue: {d in
let result = height
if platform == self.platforms.last! {
height = 0 // last item
}
return result
})
}
}
}
func item(for text: String) -> some View {
Text(text)
.padding(.all, 5)
.font(.body)
.background(Color.blue)
.foregroundColor(Color.white)
.cornerRadius(5)
}
}
struct TestWrappedLayout_Previews: PreviewProvider {
static var previews: some View {
TestWrappedLayout()
}
}
示例代码:
struct ExampleTagsView: View {
var body: some View {
ScrollView {
VStack(alignment: .leading) {
Text("Platforms:")
TestWrappedLayout()
Text("Other Platforms:")
TestWrappedLayout()
}
}
}
}
struct ExampleTagsView_Previews: PreviewProvider {
static var previews: some View {
ExampleTagsView()
}
}