Search code examples
swiftswiftuiswiftui-foreach

How can I show different view for each items of a foreach loop in swiftui?


I want to show different view for different blood groups.

let categories = ["A+", "B+", "AB+", "O+", "A-", "B-", "AB-", "O-"]
let onSelectedCategory: (String) -> ()
@State private var selectedCategory: String = ""

var body: some View {
    ScrollView(.horizontal) {
        
        HStack {
            ForEach(categories, id: \.self) { category in
                Button(action: {
                    selectedCategory = category
                    onSelectedCategory(category)
                    //Here I want to go different view for each blood group, 
                    //like APositiveView(), BPositiveView... 
                }, label: {
                    Text(category)
                }).padding(10)
                .foregroundColor(selectedCategory == category ? Color.white: Color(#colorLiteral(red: 0.204610765, green: 0.2861392498, blue: 0.3685011268, alpha: 1)))
                .background(selectedCategory == category ? Color(#colorLiteral(red: 0.4982050061, green: 0.5490344763, blue: 0.5528618097, alpha: 1)): Color(#colorLiteral(red: 0.9254772663, green: 0.9412199855, blue: 0.9449794888, alpha: 1)))
                .clipShape(RoundedRectangle(cornerRadius: 10.0, style: /*@START_MENU_TOKEN@*/.continuous/*@END_MENU_TOKEN@*/))
            }
            
        }
    }
    //.ignoresSafeArea()
}

After selecting any blood group it should shows different views for each different blood group like APositiveView(), BPositiveView()


Solution

  • Use an if statement within your HStack to display the correct view based on the value of selectedCategory:

    HStack {
        if selectedCategory == "A+" {
            APositiveView()
        } else if selectedCategory == "B+" {
            BPositiveView()
        } else if ...
        ForEach(categories, id: \.self) { category in
            // ...
        }   
    }
    

    Though a better way to approach this would be to have a single view that displays such categorical information:

    struct CategoryView: View {
        @Binding var category: String
        var body: some View {
            // Display based on the value of category
        }
    }
    
    HStack {
        CategoryView(category: $selectedCategory)
        ForEach(categories, id: \.self) { category in
            // ...
        }
    }