目标是一个菜单,其中: 用户点击绿色按钮:显示绿色菜单用户点击蓝色按钮:显示蓝色菜单
我做了什么:设置一个状态,“当点击绿色时,绿色是 ZStack 中的顶层)。
结果: 无效:当点击绿色时,它变为绿色。但后来我点击蓝色,它保持绿色。逻辑肯定不对
import SwiftUI
struct Menutest: View {
@State private var showall = false
@State private var showgreen = false
@State private var showyellow = false
@State private var showblue = false
var body: some View {
NavigationView {
HStack {
Spacer()
ZStack {
Rectangle()
.foregroundColor(.blue)
//.opacity(showblue ? 1 : 0)
.zIndex(showblue ? 1 : 0)
Rectangle()
.foregroundColor(.green)
//.opacity(showgreen ? 1 : 0)
.zIndex(showgreen ? 1 : 0)
Rectangle()
.foregroundColor(.yellow)
//.opacity(showyellow ? 1 : 0)
.zIndex(showyellow ? 1 : 0)
}
.frame(width: 400.0)
// .offset(x: showall ? 0 : UIScreen.main.bounds.width)
.animation(.easeInOut)
}
.navigationBarItems(
trailing:
HStack {
Button(action: {
// self.showall.toggle()
self.showyellow.toggle()
})
{
Text("Yellow")
}
Button(action: {
// self.showall.toggle()
self.showgreen.toggle()
})
{
Text("Green")
}
Button(action: {
// self.showall.toggle()
self.showblue.toggle()
})
{
Text("Blue")
}
}
)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct Menutest_Previews: PreviewProvider {
static var previews: some View {
Menutest()
.colorScheme(.dark)
.previewDevice("iPad Pro (12.9-inch) (3rd generation)")
}
}
Run Code Online (Sandbox Code Playgroud)
问题:如何正确设置 Zstack 以显示所选图层?不必使用 ZIndex,可以是 .hide() 修饰符或其他一些逻辑。
在我看来,如果你有几个Bool值,在任何给定时间只有一个值是真的,那么使用枚举来表示选项会更容易 - 管理状态也容易得多。这具有您期望的行为:
struct Menutest: View {
private enum Selection: String, CaseIterable {
case blue = "Blue"
case green = "Green"
case yellow = "Yellow"
static let allOptions = Array(Selection.allCases)
func color() -> Color {
switch self {
case .blue:
return .blue
case .green:
return .green
case .yellow:
return .yellow
}
}
}
@State private var showing: Selection? = nil
var body: some View {
NavigationView {
HStack {
Spacer()
ZStack {
ForEach(Selection.allOptions, id: \.self) { selection in
Rectangle()
.foregroundColor(selection.color())
.zIndex(self.showing == selection ? 1 : 0)
}
} .frame(width: 400.0)
.animation(.easeInOut)
} .navigationBarItems(trailing:
HStack {
ForEach(Selection.allOptions, id: \.self) { selection in
Button(action: { self.showing = selection }) {
Text(selection.rawValue)
}
}
})
} .navigationViewStyle(StackNavigationViewStyle())
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3413 次 |
| 最近记录: |