gpt4 book ai didi

SwiftUI:更改 ZStack .zIndex 顺序

转载 作者:行者123 更新时间:2023-12-05 08:31:20 30 4
gpt4 key购买 nike

目标是一个菜单,其中:用户点击绿色按钮:显示绿色菜单用户点击蓝色按钮:显示蓝色菜单

我做了什么:设置“当点击绿色时,绿色是 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)")
}
}

enter image description here

问题:如何正确设置 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())
}
}

关于SwiftUI:更改 ZStack .zIndex 顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076305/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com