skip to Main Content

How can I get the value of the selected row in a list?

For example:

var data: [String] = []    

List {
   ForEach(0..<data.count, id: .self) { item in
     HStack {
        Text(data[item])
     }
   }
} //: End of the List

.onDelete(perform: { indexSet in
   // get the value of the row
   // get the corresponding key for the value
   // delete the value by the key from the dictionary
}) //: End of the onDelete

.onAppear {
   let dictionary = //retrieve the data from the database and get a dictionary
   for entry in dictionary {
      data.append(entry.value)
   }
} //: End of the onAppear

How I can get the value of a selected row of the list?

2

Answers


  1. Use List with selection constructor, like

    var data: [String] = []    
    
    @State private var selection: String?
    
    List(selection: $selection) {     // << here !!
       ForEach(0..<data.count, id: .self) { item in
    // ...
    
    Login or Signup to reply.
  2. If getting value of the deleted element is a must, then you can try it this way. Code is below the image.

    If you only need the value of selected element, then just use $selection.

    enter image description here

    struct DemoView: View {
    @State var list = ["dog", "cat", "turtle"]
    @State var atIndex = 0
    @State var temp = ""
    var body: some View {
        List(selection: $temp) {
            ForEach(list, id: .self) { sub in
                HStack {
                    Text(sub)
                }
            }
            .onDelete { indexSet in
                indexSet.forEach { i in
                    atIndex += i
                }
                temp = list[atIndex]
                print("I am going to delete (temp)")
                list.remove(atOffsets: indexSet)
                atIndex = 0
            }
            Text("Recent deleted value: (temp)")
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search