Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI List with NavigationLink and Buttons

I have a List of counters - every element in the List is a counter with a number and plus/minus buttons users can click to increase or decrease the counter. Now I added a NavigationLink so that users can go to a detail view of every counter. The problem is now wherever you click on the list the detail view gets always pushed - even if you click on one of the buttons (counter increases then the detail view gets pushed via the NavigationLink) - I only want to use the NavigationLink if the user clicks on the number or somewhere else but of course not if the users clicks on of the buttons. How can this be done?

NavigationView {
        List {
            ForEach(counters, id: \.self) { counter in
                NavigationLink(destination: SingleCounterView(currentCounter: counter)) {
                    CounterCell(counter: counter)
                }
            }
        }
        .buttonStyle(PlainButtonStyle())
        .listStyle(GroupedListStyle())
}
like image 551
2092Juli Avatar asked Oct 22 '25 11:10

2092Juli


1 Answers

I've made this test, to show a CounterCell with plus and minus buttons in a NavigationView. If you tap on the buttons the counter increments, if you tap on the chevron or outside the buttons the destination appears.

@State var counters = ["a","b","c"]

var body: some View {
    NavigationView {
        List {
            ForEach(counters, id: \.self) { counter in
                NavigationLink(destination: Text(counter)) {
                    CounterCell(counter: counter)
                }
            }
        }
        .buttonStyle(PlainButtonStyle())
        .listStyle(GroupedListStyle())
    }.navigationViewStyle(StackNavigationViewStyle())
}

struct CounterCell: View {

@State var counter: String
@State var inc = 0

var body: some View {
    HStack {
        Button(action: { self.inc += 1 }) {
            Text("plus")
        }
        Button(action: { self.inc -= 1 }) {
            Text("minus")
        }
        Text(" counter: \(counter) value: \(inc)")
    }
}
}
like image 52
workingdog support Ukraine Avatar answered Oct 24 '25 01:10

workingdog support Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!