简体   繁体   English

在 SwiftUI 中使用 List 时如何使用 NavigationLink isActive 绑定?

[英]How does one use NavigationLink isActive binding when working with List in SwiftUI?

The use case is pretty simple.用例非常简单。 I have a List of places, and each corresponds to a geofence.我有一个地点列表,每个地点对应一个地理围栏。 I need to enable navigation in that particular row(s) whose geofence the user is inside.我需要在用户所在地理围栏的特定行中启用导航。 And the list is dynamic and is fetched from an API.该列表是动态的,从 API 中获取。 There are similar question on Stackoverflow, but those address only static lists. Stackoverflow 上有类似的问题,但这些问题仅针对 static 列表。

I tried using a dictionary of bools, but I am not able to make it work.我尝试使用布尔字典,但我无法使其工作。

This is a simplified mock code:这是一个简化的模拟代码:

struct ListView: View {
  @State private var navActive: [UUID: Bool] = [:]
  var body: some View {
    
           List (viewModel.allItems, id: \.id) { item in
           NavigationLink(destination: DetailView(item), isActive: $navActive[item.id]) {
             Text(item.name)
             .onTapGesture {
                if currentLocation.isInside(item.geofence) { navActive[item.id] = true }
             }
         }
      }
   }
}

I get this error: Cannot convert value of type 'Binding<Bool?>' to expected argument type 'Binding<Bool>' on the NavigationLink isActive argument.我收到此错误:无法将 NavigationLink isActive 参数上的“Binding<Bool?>”类型的值转换为预期的参数类型“Binding<Bool>”

Note: I've populated the navActive dictionary with key-value pairs on receiving allItems with an onRecieve modifier注意:我在使用 onRecieve 修饰符接收 allItems 时使用键值对填充了 navActive 字典

Here is a possible approach for your use-case这是您的用例的一种可能方法

struct ListView: View {
    
    // ... your view model defined here

    @State private var selectedItem: UUID? = nil
    var body: some View {

        List (viewModel.allItems, id: \.id) { item in
            Text(item.name)
                .onTapGesture {
                    self.selectedItem = item.id
                }
                .background(
                    NavigationLink(destination: DetailView(item), tag: item.id,
                        selection: $selectedItem) { EmptyView() }
                        .buttonStyle(PlainButtonStyle())
                )
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM