SwiftUI: List selection of custom struct

I want to have a single selection in a List, holding content of a custom struct:

struct ChannelInfo: Hashable {

    let title: String

    let description: String

}

And the view:

struct JoinChannelView: View {

    @Binding var rooms: [ChannelInfo]

    @State var selectedRoom: String?

    var body: some View {

        VStack {

            if $rooms.isEmpty {

                Text("Loading...")

                    .transition(.slide)

            } else {

                List(selection: $selectedRoom) {

                    ForEach(rooms, id: \.title) { room in

                        Text(room.title)

                            .font(.title)

                        Text(room.description)

                            .font(.subheadline)

                    }

                    .padding(.bottom)

                }

            }

        }

        .frame(width: 150, height: 300)

    }

}

My problem here is, that because inside the ForEach I render two Text views, both are selectable, but that's incorrect, I only want the title, the first Text to be selectable.

Answered by dan101 in 728652022

The ForEach should group the two Text views, together, in a common container, like a VStack, in order for both of these views to be treated as one, unique entry:

  ForEach(rooms, id: \.title) { room in
                    VStack {
                        Text(room.title)
                            .font(.title)

                        Text(room.description)

                            .font(.subheadline)
                    }
                }

Because you're using a List with selection enabled, the whole row will be selected/highlighted – that's the default behaviour.

What do you mean by only the title text be selectable? Do you only want the title text to respond to taps, or do you only want the title text to be highlighted when selected?

Accepted Answer

The ForEach should group the two Text views, together, in a common container, like a VStack, in order for both of these views to be treated as one, unique entry:

  ForEach(rooms, id: \.title) { room in
                    VStack {
                        Text(room.title)
                            .font(.title)

                        Text(room.description)

                            .font(.subheadline)
                    }
                }
SwiftUI: List selection of custom struct
 
 
Q