我在列表中有两个按钮,在点击时,列表项的整个区域都会突出显示。有没有办法将两个按钮分开?
在这种情况下,我有一个“操作”按钮和一个“信息”按钮:
我发现了这个问题,但没有直接解决方案。
这是代码:
var body: some View {
HStack {
Text(control.name)
Spacer()
Button(action: {
print("action")
}) {
Text("Action")
}
.frame(width: 250 - 10)
.padding(5)
.background(Color(white: 0.9))
.cornerRadius(10)
.frame(width: 250)
Group {
Button(action: {
print("action")
}) {
Image(systemName: "info.circle")
.foregroundColor(.accentColor)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*ton 72
将按钮样式设置为与默认不同的样式,例如 BorderlessButtonStyle()
struct Test: View {
var body: some View {
NavigationView {
List {
ForEach([
"Line 1",
"Line 2",
], id: \.self) {
item in
HStack {
Text("\(item)")
Spacer()
Button(action: { print("\(item) 1")}) {
Text("Button 1")
}
Button(action: { print("\(item) 2")}) {
Text("Button 2")
}
}
}
.onDelete { _ in }
.buttonStyle(BorderlessButtonStyle())
}
.navigationBarItems(trailing: EditButton())
}
.accentColor(.red)
}
}
Run Code Online (Sandbox Code Playgroud)
我在这个问题上挣扎了一段时间。苹果Button在SwiftUI中做出了特殊的设置。它可以根据使用的上下文进行更改。这就是为什么当a Button位于a中时我们会看到这种奇怪的功能的原因List。
幸运的是,还有其他使用.tapAction或的方式TapGesture。试试下面的代码。
var body: some View {
HStack {
Text(control.name)
Spacer()
Text("Action")
.frame(width: 250 - 10)
.padding(5)
.background(Color(white: 0.9))
.cornerRadius(10)
.frame(width: 250)
.tapAction {
print("action1")
}
Image(systemName: "info.circle")
.foregroundColor(.accentColor)
.tapAction {
print("action2")
}
}
}
Run Code Online (Sandbox Code Playgroud)
要么
var body: some View {
HStack {
Text(control.name)
Spacer()
Text("Action")
.frame(width: 250 - 10)
.padding(5)
.background(Color(white: 0.9))
.cornerRadius(10)
.frame(width: 250)
.gesture(TapGesture().onEnded() {
print("action1")
})
Image(systemName: "info.circle")
.foregroundColor(.accentColor)
.gesture(TapGesture().onEnded() {
print("action2")
})
}
}
Run Code Online (Sandbox Code Playgroud)