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

标签 ios swift swiftui

我有以下代码:

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/

相关文章:

swiftui - VStack 有最大限制吗?

SwiftUI 标签栏颜色

ios - 如何在 objective-c 中交换字符串而没有任何空格?

ios - 如何快速将正确的标注附件添加到自定义注释?

cocoa-touch - iOS 获取类似 ActionSheet 的按钮

swift - 使用 slider 在 2 个图像之间转换

ios - 如何从json存储到sqlite数据库中

ios - 在继续循环之前让后台任务完成

ios - 在 Swift 中向 NSLayoutAnchor 约束添加乘数

swift - 如何在 SwiftUI 中从一个 View 重定向到另一个 View ?