gpt4 book ai didi

list - SwiftUI - 两个独立的按钮合二为一

转载 作者:行者123 更新时间:2023-12-03 19:20:48 26 4
gpt4 key购买 nike

Xcode 11.3 (11C29).  
macOS 10.15.2.

在下面的 SwiftUI View 中有两个按钮。一个打印“OK”,另一个打印“Cancel”。但是,无论按下哪个按钮,都会执行两个打印语句。 为什么就是它? (我认为它一定是 SwiftUI 错误。)
struct ContentView: View {

var body: some View {
List {
HStack {
Button("OK") {
print("OK.")
}
Button("Cancel") {
print("Cancel")
}
}
}
}
}

(如果 ListHStack 被注释掉,那么每个按钮只打印自己的语句。)

最佳答案

您可以使用 .buttonStyle(BorderlessButtonStyle())以达到预期的效果。如果你想在你的 List 里面有按钮,它允许您单独点击以及 List行也是如此。

这是一个带有 ForEach(..) 的实现环形:

struct ContentView: View {
var body: some View {
List {
ForEach(["My List Item Buttons"], id: \.self) {
item in
HStack {
Text("\(item)")
Spacer()
Button(action: { print("\(item) 1")}) {
Text("OK")
}
Button(action: { print("\(item) 2")}) {
Text("Cancel")
}
}
}
.buttonStyle(BorderlessButtonStyle())
}
}
}

As a convenience, the List initialiser also allows you to use it just like the above ForEach view in case you want to have a list consisting of a single cell type only.


List(["My List Item Buttons"], id: \.self) { item in
Text("Row \(row)")
}

或者像这样的东西没有:
struct ContentView: View {
var body: some View {
List {
HStack {
Button(action: { print("OK")}) {
Text("OK")
}
Button(action: { print("Cancel")}) {
Text("Cancel")
}
}
.buttonStyle(BorderlessButtonStyle())
}
}
}

关于list - SwiftUI - 两个独立的按钮合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59349193/

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