4

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())
}

1 Answer 1

9

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)")
    }
}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank for the answer. I had added a custom ButtonStyle and the ScaleEffect somehow changed this behaviour. struct PlusButton: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration.label .scaleEffect(configuration.isPressed ? 0.8 : 1.0) } }
I've added your button style to the plus button, and it still works for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.