Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Navigation Link containing a Button

I have a SwiftUI list that looks like this:

List {
    ForEach(items) { item in
    NavigationLink(destination: EditItemView(item: item)) {
        ItemView(item: item, buttonAction: {
            // Do something
        })
    }
}

where ItemView is:

struct ItemView: View {
    var item: Item
    let buttonAction: () -> Void

    var body: some View {
        HStack(alignment: .center) {
            Text(item.tile)
                    .font(.headline)
            Spacer()
            Button(action: buttonAction,
                   label: {
                    Image(systemName: "plus.circle")
                   })
                  .padding(.horizontal)
        }
    }
}

However, whenever I tap on the button, instead of performing the button action it goes to the EditItemView which is the navigation link action.

So how can I have a button performing an action inside a navigation link?

Or if that is not possible, how can I make that tapping the item view does one action and tapping the button does another action?

like image 851
nikmin Avatar asked Mar 11 '26 08:03

nikmin


1 Answers

Here is possible approach - changed only ItemView by replacing default button with tap gesture (tested with Xcode 12 / iOS 14)

struct ItemView: View {
    var item: Int
    let buttonAction: () -> Void

    var body: some View {
        HStack(alignment: .center) {
            Text("Item \(item)")
                .font(.headline)
            Spacer()
            Image(systemName: "plus.circle")
                .padding(.horizontal).contentShape(Rectangle())
                .highPriorityGesture(TapGesture().onEnded(buttonAction))
        }
    }
}
like image 52
Asperi Avatar answered Mar 13 '26 06:03

Asperi



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!