Update EmptyView 是一个辅助视图,它在声明树中占用空间,但不在屏幕上。这是一个使用滑块动态设置横幅中项目数量的示例。当超过阈值时, EmptyView 作为第二个成员换入。
struct HysteresisView: View {
@State var count : CGFloat = 10
let threshold : CGFloat = 125
var rectangles = [BannerItem]()
init() {
(0..<10).forEach { n in
let color = UIColor(hue: CGFloat.random(in: 0...1), saturation: 0.75, brightness: 0.75, alpha: 1)
let width = CGFloat.random(in: 30...100)
rectangles.append(BannerItem(id: n, color: Color(color), width: width))
}
}
var body: some View {
VStack {
Slider(value: $count, in: 1...10, label: { Text("Show this many") })
HStack {
ForEach(rectangles.filter({ $0.id < Int(count) }), id: \.id) { rectangle in
Rectangle().foregroundColor(rectangle.color).frame(width: rectangle.width, height: 30)
}
Spacer()
GeometryReader { geo in
HStack {
if geo.size.width > threshold {
Text("Optional View")
} else {
EmptyView()
}
}
.frame(width: threshold)
.background(Color.gray)
}
}.frame(height: 25)
Spacer()
}
}
struct BannerItem {
let id : Int
let color : Color
let width : CGFloat
}
}