You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中Dynamic NavigationLink实现卡片动态跳转不同页面的问题

解决方案

1. 修改数据源相关代码

首先在你的数据源文件中新增跳转目标枚举,同时更新Item结构增加跳转目标标识字段:

// 定义所有卡片对应的跳转目标
enum CardDestination {
    case aboutA
    case aboutB
}

struct Item: Identifiable {
    var id = UUID()
    var title: String
    var text: String
    var image: String
    var destination: CardDestination // 新增字段,标记当前卡片要跳转的页面
}

初始化你的items数组时,分别给两张卡片指定对应的跳转目标:

let items = [
    Item(title: "卡片A标题", text: "卡片A说明", image: "图片A名", destination: .aboutA),
    Item(title: "卡片B标题", text: "卡片B说明", image: "图片B名", destination: .aboutB)
]

2. 修改HomeView中的导航逻辑

把原来硬编码的AboutA()改为根据当前item的destination字段动态返回对应页面:

ForEach(items) { item in
    NavigationLink(destination: {
        switch item.destination {
        case .aboutA:
            return AnyView(AboutA())
        case .aboutB:
            return AnyView(AboutB())
        }
    }()) {
        CardView(item: item)
    }
}

注:用AnyView包装是为了统一不同视图类型的返回值,适配所有SwiftUI版本。如果你的项目最低支持iOS 15及以上,也可以用Group包裹两个case的返回值,不需要加AnyView。

内容的提问来源于stack exchange,提问作者Branko Djondovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:45:02