在下面的 foreach 循环中,我在水平堆栈中创建一个按钮来删除数组中的该对象,但是不仅仅是按钮可按下,整行都是可按下的,这不是我正在寻找的设计。任何帮助将不胜感激:)
struct myView:View{
@EnvironmentObject var getFood:FoodAddModel
@EnvironmentObject var person: UserInfoModel
var unwrappedFoods:[AddedFoods]{
getFood.foods ?? []
}
var body: some View{
List{
ForEach(Array(unwrappedFoods.enumerated()), id: \.1.id) { (index, obj) in
HStack{
HStack{
Text(obj.name)
Button(action: {
getFood.foods?.remove(at: index)
person.personCurrentCalorieProgress.calorieProgress += obj.totalCals
}) {
Image(systemName: "minus").foregroundColor(.red)
}
}
}
}
}
}
}
List
似乎对按钮的行为很奇怪,作为解决方法,您可以使用带有值 plainButtonStyle()
的buttonStyle 修饰符
import SwiftUI
struct myView:View{
var body: some View{
List{
ForEach(0..<5) { (index) in
HStack{
Text("\(index)")
Spacer()
Button(action: {
print("foo")
}) {
Image(systemName: "minus").foregroundColor(.red)
}.buttonStyle(PlainButtonStyle())
}
}
}
}
}
为了解决问题,您应该使用图像而不是按钮,因为列表会导致此问题发生!列出所有行的应用按钮操作,而不仅仅是按钮!
struct myView:View{
@EnvironmentObject var getFood:FoodAddModel
@EnvironmentObject var person: UserInfoModel
var unwrappedFoods:[AddedFoods]{
getFood.foods ?? []
}
var body: some View{
List{
ForEach(Array(unwrappedFoods.enumerated()), id: \.1.id) { (index, obj) in
HStack{
Text(obj.name)
Spacer()
Image(systemName: "minus")
.frame(width: 40, height: 40, alignment: .center) // <<: Here
.background(Color.white) // <<: Here
.foregroundColor(.red)
.onTapGesture { // <<: Here
getFood.foods?.remove(at: index)
person.personCurrentCalorieProgress.calorieProgress += obj.totalCals
}
}
}
}
}
}
如果有人遇到“整个列表项视图可按下”的问题,只需添加值为 plainButtonStyle() 的 ButtonStyle 修饰符。通过这种方法列表可以正常工作。
VStack(spacing: 0.0) {
Button{
action
}
label: {
Text("Take Quiz")
.foregroundColor(Color.blue)
.padding(.vertical,4)
.padding(.horizontal)
.frame(maxWidth:.infinity,alignment:.center)
.overlay{
Capsule()
.stroke(Color.blue,lineWidth: 2)
}
}.buttonStyle(PlainButtonStyle())
}
.frame(maxWidth:.infinity,alignment:.center)
.padding([.horizontal,.bottom])