简体   繁体   中英

SwiftUI: Is there a way to create a list with single selection (like in iOS Settings)?

I am currently building my first iOS app with Swift UI and I was wondering if there is any standard way in Swift UI to allow for single selection in a list. Just like is the case in the iOS settings (see screenshot below).

1

Thanks for your help in advance!

Meanwhile found an answer thanks to example code on hackingwithswift.com

struct ContentView: View {
var strengths = ["Mild", "Medium", "Mature"]

@State private var selectedStrength = 0

var body: some View {
    NavigationView {
        Form {
            Section {
                Picker(selection: $selectedStrength, label: Text("Strength")) {
                    ForEach(0 ..< strengths.count) {
                        Text(self.strengths[$0])

                        }
                    }
                }
            }.navigationBarTitle("Select your cheese")

        }
    }
}

This is what I used for single selection for SwiftUI ForEach

 @State private var selectedTimeSlotBtn: Int = 0
 @State private var timeSlots = ["15s","30s","60s","∞"]

 ForEach(0..<timeSlots.count) { item in
                                    Button {
                                        self.selectedTimeSlotBtn =item
                                    } label: {
                                        Text(timeSlots[item])
                                            .frame(width: 39, height: 26, alignment: .center)
                                            .foregroundColor(Color.white)
                                            .background(self.selectedTimeSlotBtn == item ? Color("clifie_light_green_com") : Color("clifie_dark_gray"))
                                            .cornerRadius(12)
                                            .padding(.trailing, 2)
                                            .padding(.leading, 2)
                                    }
                   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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