结构之间的@binding问题

马特·内维斯(Matt Neves)

在我的代码中,我有:

struct Specialty {
    let type:String
    let color:Color
    let image:Image
}

// MARK: Search
struct Search: View {
   
    @State var show = false
    @State var txt = ""
    @State  var index = 1
    let specialtyList = [
        Specialty(type: "Cardiologia", color: Color.blue, image: Image("google1") ),
        Specialty(type: "Clínica Médica", color: Color.pink, image: Image("google1")),
        Specialty(type: "Dermatologia", color: Color("Color"), image: Image("google1")),
        Specialty(type: "Ginecologia e Obstetrícia", color: Color.pink, image: Image("google1")),
        Specialty(type: "Medicina do Trabalho", color: Color.red, image: Image("google1")),
        Specialty(type: "Oftalmologia", color: Color("Color"), image: Image("google1")),
        Specialty(type: "Ortopedia", color: Color.pink, image: Image("google1")),
        Specialty(type: "Otorrinolaringologia", color: Color.blue, image: Image("google1")),
        Specialty(type: "Pediatria", color: Color.red, image: Image("google1")),
        Specialty(type: "Psiquiatria", color: Color("Color"), image: Image("google1")),
        Specialty(type: "Radiologia", color: Color("Color"), image: Image("google1"))
    ]
}

忽略相同的google1图片,我只是想让代码先工作。

然后,在搜索视图中,我有:

ForEach(specialtyList, id: \.type){ Specialty in
    NavigationLink (destination: SearchBar()){
        VStack(spacing: 18) {
            HStack{
                Text(Specialty.type).foregroundColor(.white)
                Specialty.image
                    .renderingMode(.original)
                    .resizable()
                    .frame(width: 35, height: 35)
            }
        }
    }
}

以“ scrollView”的形式显示“ let specialList”中的信息

因为每个显示的世界都像一个按钮,所以我尝试这样做,当我到达目的地(在本例中为SearchBar())时,我希望根据所按下的NavigationLink文本显示不同的信息。

如何使用列表“ specialtyList”中的顺序来执行此操作,如何在目标位置简单地打印与所按下的NavigationLink文本相同的名称?

他的脾气

我想就是这样

注意:尝试避免对类型(例如,Specialty,大写)和实例/值(例如,Specialty,小写)进行相同的命名,否则可能会使编译器和您感到困惑。

ForEach(specialtyList, id: \.type){ specialty in   // << named correctly
    NavigationLink (destination: SearchBar(item: specialty)){  //  << inject here
        VStack(spacing: 18) {
            HStack{
                Text(specialty.type).foregroundColor(.white)
                specialty.image
                    .renderingMode(.original)
                    .resizable()
                    .frame(width: 35, height: 35)
            }
        }
    }
}

现在来看

struct SearchBar: View {
   let item: Specialty

   var body: some View {
      Text(item.type)

      // .. other code
   }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章