swiftuiswiftui-list

SwiftUI List row HIGHLIGHT animation on tap WITHOUT NavigationLink


SwiftUI List will automatically highlight the tapped row, iff there is a NavigationLink inside.

Since I use SwiftUI embedded in UIKit via UIHostingController, I handle my navigation with a UINavigationController, so I do not want to use NavigationLink.

However, I need the List rows to be highlighted on tap, which is not there when using .onTapGesture

How can I do that?

Here is an example:

List {
    Section(header: Text("Section header text")) {
        HStack { // A row in the list
                Image(systemName: "circle")
                VStack(alignment: .leading) {
                    Text("profile name")
                    // Sub label
                    Text("Description")
                        .foregroundColor(.secondary)
                        .font(.system(size: 12))
            }
            Spacer()
        }
        .contentShape(Rectangle())
        .onTapGesture { // Detect tap on the row
            Print("Perform action here...")
            // THE TAP IS NOT ANIMATED BECAUSE THERE IS NO NAVIGATION LINK HERE.
        }
    }
}

Solution

  • why not use Button()

    struct ContentView: View {
    var body: some View {
        List {
            Section(header: Text("Section header text")) {
                
                Button(action: {
                    print("Perform action here...")
                    
                }, label: {
                    HStack { // A row in the list
                            Image(systemName: "circle")
                            .foregroundColor(.primary)
                            VStack(alignment: .leading) {
                                Text("profile name")
                                    .foregroundColor(.primary)
                                // Sub label
                                Text("Description")
                                    .foregroundColor(.secondary)
                                    .font(.system(size: 12))
                        }
                        Spacer()
                    }
                })
                .contentShape(Rectangle())
                
            }
        }
    }
    }
    

    enter image description here