UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Button's action being run when clicking anywhere in HStack surrounding it

Forums > SwiftUI

I have the following code and want to increment the activity count every time I click the button. It turns out, clicking anywhere in the HStack triggers the button click event. Is this a SwiftUI bug or am I missing something here?

struct ContentView: View {
    @ObservedObject var activities = Activities()
    @State private var showingNewActivityScreen = false

    var body: some View {
        NavigationView {
            List {
                ForEach(activities.items) { activity in
                    HStack {
                        Text("\(activity.title)")
                            .padding([.horizontal])

                        Spacer()

                        Text("\(activity.count)").padding(.horizontal)
                        Button(action: {
                            let currentTrackerIndex = self.activities.items.firstIndex { $0 == activity }
                            if let index = currentTrackerIndex { self.activities.items[index].count += 1 }
                        }) { Image(systemName: "plus").frame(width: 32, height: 32) }
                    }
                    .padding([.horizontal, .vertical], 5)
                    .background(Color.blue)
                    .foregroundColor(Color.white)
                    .clipShape(RoundedRectangle(cornerRadius: 16))
                }
            }
            .onAppear { UITableView.appearance().separatorStyle = .none }
            .navigationBarTitle("Habit Tracking")
            .navigationBarItems(trailing:
                Button(action: { self.showingNewActivityScreen = true },
                       label: { Text("New") } )
            )
        }
        .sheet(isPresented: $showingNewActivityScreen, content: { RegisterActivity(activities: self.activities, "New activity") })
    }
}

4      

I don't know all the particulars, but after many searches for how to have multiple buttons on a list row, it's expected behavior...whether that's good or bad is another discussion.

To achieve your desired behavior, add .buttonStyle(BorderlessButtonStyle()).

Also, because it's bit me so many times, I try to avoid setting specific frame sizes. With Image(systemName: "plus") you can use something like .font(Font.system(.body).weight(.bold)) to change the appearance and let SwiftUI work its magic.

7      

@danieleprice1, thank you for the fix and the tip. This behaviour is quite counter-intuitive.

3      

What's funny is that I have another screen where I have two Buttons (separated by a Spacer) in an HStack, and they work as intended.

3      

It's not the HStack that causes the problem, but the List.

5      

Thanks for this solution, this was confusing me.

Coming from HTML and CSS to SwiftUI this behavior is not intuitive or expected that a button would overlap everything in the row or HStack without an easy way to set a z-index like you do in HTML.

3      

Thanks! I ran into the same issue (Button at the end of a TextField). Thankfully you guys already solved it!

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.