SwiftUI - 列表行中的多个按钮 [英] SwiftUI - Multiple Buttons in a List row

查看:26
本文介绍了SwiftUI - 列表行中的多个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 List 和一行中的两个按钮,如何在没有整行突出显示的情况下区分哪个按钮被点击?

Say I have a List and two buttons in one row, how can I distinguish which button is tapped without the entire row highlighting?

对于此示例代码,当点击行中的任何一个按钮时,两个按钮的动作回调都会被调用.

For this sample code, when any one of the buttons in the row is tapped, both button's action callbacks are invoked.

// a simple list with just one row
List {

    // both buttons in a HStack so that they appear in a single row
    HStack {
        Button {
            print("button 1 tapped")
        } label: {
            Text("One")
        }
            
        Button {
            print("button 2 tapped")
        } label: {
            Text("Two")
        }
    }
}

当只有一个按钮被点击一次时,我看到两个按钮的回调都被调用,这不是我想要的:

When only one of buttons is tapped once, I see the callbacks for both buttons being called, which is not what I want:

button 1 tapped
button 2 tapped

推荐答案

您需要使用 BorderlessButtonStyle()PlainButtonStyle().

    List([1, 2, 3], id: .self) { row in
        HStack {
            Button(action: { print("Button at (row)") }) {
                Text("Row: (row) Name: A")
            }
            .buttonStyle(BorderlessButtonStyle())
            
            Button(action: { print("Button at (row)") }) {
                Text("Row: (row) Name: B")
            }
            .buttonStyle(PlainButtonStyle())
        }
    }

这篇关于SwiftUI - 列表行中的多个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆