如何让按钮标签中的文本符合Grid和GridRow?

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

当我迭代数据表并使用

GridRow
内的
Grid
呈现内容时,一切都按照我的预期对齐。

VStack {
    Text(table.name)
    Grid {
        ForEach(currents) { current in
           GridRow {
               Text(current.type)
                   .gridColumnAlignment(.trailing)
               Text(current.time)
                   .gridColumnAlignment(.center)
               Text(current.speed)
                   .gridColumnAlignment(.center)
           }
        }
    }
}

但是,当我尝试通过将每一行放入

label
中来使每一行成为可点击按钮时,它似乎不再意识到前一个
GridRow

设置的间距
VStack {
    Text(table.name)
    Grid {
        ForEach(currents) { current in
            Button {
                selectedCurrent = current
                // do something
            } label: {
                GridRow {
                    Text(current.type)
                        .gridColumnAlignment(.trailing)
                    Text(current.time)
                        .gridColumnAlignment(.center)
                    Text(current.speed)
                        .gridColumnAlignment(.center)
                }
            }
        }
    }
}

如何在使每一行成为可点击按钮的同时保持

Grid
GridRow
间距的完整性?

button swiftui grid
1个回答
0
投票

您可以尝试这种替代方法:在每行上添加手势并将

foregroundColor
设置为蓝色以使其可点击。

VStack {
    Text(table.name)
    Grid {
        ForEach(currents) { current in
            GridRow {
                Text(current.type)
                    .gridColumnAlignment(.trailing)
                Text(current.time)
                    .gridColumnAlignment(.center)
                Text(current.speed)
                    .gridColumnAlignment(.center)
            }
            .foregroundColor(.blue)
            .onTapGesture {   
                selectedCurrent = current
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.