SwiftUI中另一个按钮中的按钮

问题描述 投票:0回答:1

如何才能使内 Button 执行它的动作,而不是总是执行外部的动作?

struct Foo: View {
    var body: some View {
        Button(action: { print("alloha") }) {
            HStack {
                Button(action: { print("hello") }) {
                    Image(systemName: "circle.fill")
                }
                Text("world")
                Spacer()
            }
        }
    }
}
ios swift button swiftui
1个回答
0
投票

它的工作原理是,只要给内部按钮足够的空间,所以点击测试可以指定激活哪个按钮,就像下面的例子。(用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()
            }
        }
    }
}

0
投票

我很好奇为什么你要在一个按钮里面添加按钮?我可以在一个HStack中使用两个按钮,就像下面的例子。当用户点击每个按钮时,它将会很明显。

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

    Button(action: {
        print("World")
    }) {
        Text("World")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.