Button inside another button in SwiftUI

Viewed 2355

How can I make the inner Button execute its action instead of the outer one always being performed?

struct Foo: View {
    var body: some View {
        Button(action: { print("alloha") }) {
            HStack {
                Button(action: { print("hello") }) {
                    Image(systemName: "circle.fill")
                }
                Text("world")
                Spacer()
            }
        }
    }
}
2 Answers

It works, just give enough space for internal button, so hit testing could designate which button to activate, like in below example. (Tested with Xcode 11.4 / iOS 13.4)

demo

struct Foo: View {
    var body: some View {
        Button(action: { print("alloha") }) {
            HStack {
                Button(action: { print("hello") }) {
                    Image(systemName: "circle.fill").padding() // << more space !!
                        .border(Color.red) // << for testing
                }
                Text("world")
                Spacer()
            }
        }
    }
}

I am curious why you are adding button inside a button? I could use Two Buttons within a HStack like below. It will be obvious to user when tapping each buttons.

HStack {
    Button(action: { print("hello") }) {
        Image(systemName: "circle.fill")
    }

    Button(action: {
        print("World")
    }) {
        Text("World")
    }
}
Related