在 SwiftUI 中使用 List 时,如何使用 NavigationLink isActive 绑定? [英] How does one use NavigationLink isActive binding when working with List in SwiftUI?

查看:41
本文介绍了在 SwiftUI 中使用 List 时,如何使用 NavigationLink isActive 绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用例非常简单.我有一个地点列表,每个地点对应一个地理围栏.我需要在用户位于其地理围栏内的特定行中启用导航.该列表是动态的,是从 API 中获取的.Stackoverflow 上也有类似的问题,但那些只针对静态列表.

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. There are similar question on Stackoverflow, but those address only static lists.

我尝试使用 bool 字典,但无法使其正常工作.

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 }
             }
         }
      }
   }
}

我收到此错误:无法转换类型为 'Binding' 的值到预期的参数类型 'Binding'在 NavigationLink isActive 参数上.

I get this error: Cannot convert value of type 'Binding<Bool?>' to expected argument type 'Binding<Bool>' on the NavigationLink isActive argument.

注意:在接收带有 onRecieve 修饰符的 allItems 时,我已经用键值对填充了 navActive 字典

Note: I've populated the navActive dictionary with key-value pairs on receiving allItems with an onRecieve modifier

推荐答案

这是您的用例的一种可能方法

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())
                )
        }
    }
}

这篇关于在 SwiftUI 中使用 List 时,如何使用 NavigationLink isActive 绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆