gpt4 book ai didi

ios - SwiftUI List ForEach View 中的按钮即使不是 "tapped"也会触发?

转载 作者:行者123 更新时间:2023-12-02 01:50:38 25 4
gpt4 key购买 nike

我有以下代码:

struct ButtonTapTest: View {

let items = [1, 2, 3]

var body: some View {

List {
ForEach(items, id:\.self) { item in
CellTestView()
}
}

}
}


struct CellTestView:View {


var body: some View {

VStack {

Button {
print("TOP")
} label: {
Image(systemName: "play.fill")
.font(.system(size: 40))
.foregroundColor(.red)
}
.border(.red)

Spacer()

Button {
print("BOTTOM")

} label: {
Image(systemName: "play")
.font(.system(size: 40))
.foregroundColor(.red)
}
.border(.yellow)

}

}

}

创建以下屏幕:

enter image description here

问题:

无论我点击 CellTestView 的哪个位置,单元格中的两个按钮操作都会被触发。我希望单独的按钮操作单独触发,每个按钮仅在其按钮被点击时触发,而不是在我点击单元格上其他任何地方的外部时触发。

您可以在下面的 gif 中看到,无论我点击 CellTestView 的哪个位置,无论我点击 View 的哪个位置,两个按钮操作都会触发,“TOP”和“BOTTOM” "日志同时触发。

如何解决此问题,以便单元格中的两个按钮独立接收点击,并且仅当点击位于相关按钮内时?

enter image description here

最佳答案

每当列表行中有多个按钮时,您需要手动将按钮样式设置为.borderless.plain。这是因为按钮“适应”了它们的上下文。根据documentation :

If you create a button inside a container, like a List, the style resolves to the recommended style for buttons inside that container for that specific platform.

因此,当您的按钮位于列表中时,其点击目标会扩展以填充该行,并且您会获得高亮动画。当你有超过 2 个按钮时,SwiftUI 不够聪明,无法阻止这种副作用,所以你需要设置 buttonStyle手动。

CellTestView()
.buttonStyle(.borderless)

结果:

Tapping top and bottom button results in separate print statements

关于ios - SwiftUI List ForEach View 中的按钮即使不是 "tapped"也会触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70399810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com