首页 > 解决方案 > 在 SwiftUI 中,我如何区分一般点击与单元格中的按钮点击?

问题描述

我有一个列表,每个项目都有一个 NavigationLink 和一个 ZStack 中的单元格视图。

List(inventory.items) { food in
    ZStack {
        NavigationLink(
            destination: InventoryEditionView(food: food, index:inventory.items.firstIndex(of: food)!))
                         {
                         EmptyView()
                         }
                        .disabled(!model.seletedFoodItems.isEmpty)

        InventoryListCell(food: food, model: model)
                        
    }
 }

在单元格视图中,我打勾以允许用户进行多项选择。

Button{
            
            if model.isSelected(food: food) {
                model.deselect(food)
            } else {
                model.select(food)
            }

        } label: {
            Image(systemName: "checkmark.circle")
                .frame(width: 44, height: 44)
                .imageScale(.large)
                .foregroundColor(model.isSelected(food: food) ? Color("primary") : Color(.systemGray))
            
        }

但是,无论我在单元格视图中点击什么位置,它都会触发选择。是否可以仅在点击选中标记时触发选择?

标签: iosswiftui

解决方案


你可以尝试使用

.allowsHitTesting(false) 

在您不想触发选择的视图上点击时“关闭”选择。


推荐阅读