Home > Back-end >  How to create dropdown in Swift UI?
How to create dropdown in Swift UI?

Time:05-20

I was trying to create a dropdown in Swift UI. Most of the article suggested to use overlay to create the same. Tried some sample code below, However the when drop down comes up it does come in below the next content.Preview 1

Preview 2

You can use the combination of GroupBox and DisclosureGroup to achieve what you're looking for, you can modify below code according to your requirements

import SwiftUI

struct ContentView: View {
    //MARK: - PROPERTIES
    
    let nutrients: [String] = ["Energy", "Sugar", "Fat", "Protein", "Vitamins", "Minerals"]
    
    //MARK: - BODY
    
    var body: some View{
        GroupBox(){
            DisclosureGroup("Nutritional value per 100g") {
                ForEach(0..<nutrients.count, id: \.self){ index in
                    Divider()
                        .padding(.vertical, 2)
                    
                    HStack{
                        Group{
                            Image(systemName: "info.circle")
                            Text(nutrients[index])
                        }//: GROUP
                        .foregroundColor(.gray)
                        .font(.system(.body).bold())
                        
                        Spacer(minLength: 25)
                        
                        Text("1g")
                            .multilineTextAlignment(.trailing)
                    }//: HSTACK
                }//: LOOP
            }//: DISCLOSURE
        }//: BOX
    }
}

//MARK: - PREVIEW

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
  • Related