SwiftUI NavigationStack中如何区分同类型值的NavigationLink目标
因为两个NavigationLink传递的都是Int类型值,系统无法自动区分对应的跳转目标,这里提供几种实用的解决方法:
方法一:定义专属枚举类型
通过枚举的不同case明确区分跳转意图,同时可关联对应数值,代码清晰易维护:
// 定义遵循Hashable的枚举(NavigationStack要求值类型必须实现Hashable) enum NavigationTarget: Hashable { case followers(Int) case following(Int) } // 使用方式 NavigationLink(value: NavigationTarget.followers(user.followersCount)) { Text("Followers") } NavigationLink(value: NavigationTarget.following(user.followingCount)) { Text("Following") } // 对应跳转目标 .navigationDestination(for: NavigationTarget.self) { target in switch target { case .followers(let count): FollowersView(count: count) // 可直接传递数值给视图 case .following(let count): FollowingView(count: count) } }
方法二:创建专属标识结构体
为每个跳转目标定义独立的结构体包装数值,让系统识别不同跳转类型:
// 定义专属结构体,只需遵循Hashable struct FollowersCount: Hashable { let value: Int } struct FollowingCount: Hashable { let value: Int } // 使用方式 NavigationLink(value: FollowersCount(value: user.followersCount)) { Text("Followers") } NavigationLink(value: FollowingCount(value: user.followingCount)) { Text("Following") } // 对应跳转目标 .navigationDestination(for: FollowersCount.self) { count in FollowersView(count: count.value) } .navigationDestination(for: FollowingCount.self) { count in FollowingView(count: count.value) }
方法三:使用带标识的元组(简洁但可读性稍弱)
利用元组同时传递数值和类型标识,元组默认遵循Hashable(内部元素需实现Hashable):
// 使用方式,元组第一个元素作为类型标识,第二个是数值 NavigationLink(value: ("followers", user.followersCount)) { Text("Followers") } NavigationLink(value: ("following", user.followingCount)) { Text("Following") } // 对应跳转目标 .navigationDestination(for: (String, Int).self) { tuple in switch tuple.0 { case "followers": FollowersView(count: tuple.1) case "following": FollowingView(count: tuple.1) default: EmptyView() } }
推荐优先使用方法一,枚举类型的可读性和扩展性最优,后续新增跳转类型时直接添加case即可。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

