ปัญหาเกี่ยวกับ @binding ระหว่างโครงสร้าง

Aug 17 2020

ในรหัสของฉันฉันมี:

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)
            }
        }
    }
}

เพื่อแสดงข้อมูลใน 'let specialtyList' เป็น scrollView

ในขณะที่โลกแต่ละใบที่แสดงทำงานเป็นปุ่มฉันพยายามอย่างนั้นเมื่อฉันไปที่ปลายทาง (ซึ่งก็คือ SearchBar () ในกรณีนี้) ฉันต้องการให้แสดงข้อมูลที่แตกต่างกันขึ้นอยู่กับข้อความ NavigationLink ที่กด

ฉันจะทำได้อย่างไรโดยใช้คำสั่งในรายการ "specialtyList" และจะพิมพ์ข้อความ NavigationLink ชื่อเดียวกับปลายทางที่กดได้อย่างไร

คำตอบ

Asperi Aug 17 2020 at 10:42

ฉันคิดว่านี่คือมัน

หมายเหตุ: พยายามหลีกเลี่ยงการตั้งชื่อแบบเดียวกันสำหรับประเภท (เช่นแบบพิเศษตัวพิมพ์ใหญ่) และอินสแตนซ์ / ค่า (เช่นแบบพิเศษลดขนาด) มิฉะนั้นอาจทำให้สับสนและคอมไพเลอร์และคุณ

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
   }
}