繁体   English   中英

Swiftui foreach 在一组按钮上循环

[英]Swiftui foreach looping on an array of buttons

当在循环中按下一个按钮时,它的背景颜色变为红色,当按下另一个按钮时它的颜色也变为红色。 但剩下的按钮仍然是红色,不会再次变为蓝色。 如何只将按下的按钮更改为红色,而将其他按钮更改为蓝色?

struct Box: Identifiable  {
    var id: Int
    var title: String
}

struct MainView: View {


    let boxes:[Box] = [
    Box(id: 0, title: "Home"),
    Box(id: 1, title: "Subjects"),
    Box(id: 2, title: "attendence"),
    Box(id: 3, title: "H.W"),
    Box(id: 4, title: "Quizes"),
    Box(id: 5, title: "class schedule"),
    Box(id: 6, title: "Exam Schedule"),
    Box(id: 7, title: "Inbox"),
    Box(id: 8, title: "Evalouation"),
    ]

    @Binding var showMenu: Bool

    var body: some View{
    VStack {
        ScrollView(.horizontal,showsIndicators: false){
                HStack{
                    ForEach(boxes, id: \.id) {
                        box in
                        BoxView(box: box)
                    }

                }
            }


        }.padding()

    }
}

struct BoxView: View {
    @State var selectedBtn: Int = 1
    var box: Box
    var body: some View{
        Button(action: {
            self.selectedBtn = self.box.id

        }){
            Text(box.title)
                .foregroundColor(.white)
        }
    .frame(width: 130, height: 50)
        .background(self.selectedBtn == self.box.id ? Color.red : Color.blue)
    .cornerRadius(25)
    .shadow(radius: 10)
    .padding(10)

    }
}

这有效:

1) 添加一个@State到 MainView 以跟踪所选按钮

2) 将此状态作为绑定传递给 BoxView

3) 在 BoxView 上将@State更改为@Binding (= in-out state)

struct MainView: View {
  [...]
  @Binding var showMenu: Bool
  @State var selected = 0    // 1
  var body: some View{
    VStack {
      ScrollView(.horizontal,showsIndicators: false){
        HStack{
          ForEach(boxes, id: \.id) { box in
            BoxView(box: box, selectedBtn: self.$selected)  // 2
          }
        }
      }
    }.padding()
  }
}

struct BoxView: View {
  var box: Box
  @Binding var selectedBtn: Int  // 3 
  var body: some View{
    Button(action: {
      self.selectedBtn = self.box.id
    }){
      Text(box.title)
       .foregroundColor(.white)
    }
    .frame(width: 130, height: 50)
    .background(self.selectedBtn == self.box.id ? Color.red : Color.blue)
    .cornerRadius(25)
    .shadow(radius: 10)
    .padding(10)
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM