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

问题描述

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

Say I have a List and two buttons in one row, how to ditinguish 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(action: {
            print("button 1 tapped")
        }) {
            Text("One")
        }

        Button(action: {
            print("button 2 tapped")
        }) {
            Text("Two")
        }
    }
}

// when tapping just once on either button:
// "button 1 tapped"
// "button 2 tapped"

推荐答案

您需要使用 BorderlessButtonStyle() .

You need to use BorderlessButtonStyle().

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

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

09-02 09:07