iosswiftxcodeswiftuiswiftui-list

Row gets unselected list swiftUI


List(viewModel.surahs, selection: $selected) { surah in
    Button {
        selected = surah.id
    } label: {
        HStack {
            Text(surah.name.transliteration.en)
            Spacer()
            Text(surah.name.short)
        }
    }
}
.listStyle(.plain)

This is my list in SwiftUI.

  • What I want: When user taps on a row the row stays highlighted.
  • But what I get: On each tap the row gets selected and unselected within a fraction of seconds.
  • One more thing: If I add or subtract 1 with surah.id in line no 3, upon tapping on a row the next or previous row stays selected. (I mean when I use selected = surah.id + 1 or selected = surah.id - 1 instead of selected = surah.id

Solution

  • To achieve what you describe and trigger a function when you select a row, attach .onChange(of: selected) {...} to the List.

    For example:

     List(surahs, selection: $selected){ surah in
         HStack{
             Text(surah.name.transliteration.en)
             Spacer()
             Text(surah.name.short)
         }
     }
     .onChange(of: selected) {
         print("-----> do something here")
         // if selected ... else ....
     }
     .listStyle(.plain)