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

NavigationLink的isActive已废弃,如何在.background()中重写实现?

我在Codecademy学习SwiftUI课程时遇到了问题,原代码使用了已废弃的NavigationLink的isActive参数,通过.background()里的隐藏导航链接实现当商品数量为0时自动跳转。现在需要改用NavigationStack和.navigationDestination,但不知道怎么实现原逻辑。原代码如下:

@State var quantityRemaining = Int.random(in: 1...10)
let itemName: String

var body: some View {
  VStack {
    Text("\(itemName)")
      .font(.title)
      .padding()
    Spacer()
    Image(systemName: "photo")
      .font(.system(size: 200))
      .padding()
    Text("Quantity Remaining: \(quantityRemaining)")
    Spacer()
    Button {
      if quantityRemaining > 0 {
        quantityRemaining -= 1
      }
    } label: {
      Text("Add one to your cart")
    }
    Spacer()
  }
  // .background() runs the view below in the background
  .background(
    // The navigation link is not active until the quantity is 0
    NavigationLink(destination: Text("You bought all the \(itemName)!"),
                   isActive: .constant(quantityRemaining == 0),
                   label: { EmptyView() })
  )
}

解决方案

要实现原逻辑,只需调整导航架构并通过状态变量控制跳转,具体步骤如下:

  • 用NavigationStack包裹整个视图层级
  • 新增@State变量控制跳转触发状态
  • 在按钮点击逻辑中,当商品数量归0时激活跳转状态
  • 通过.navigationDestination绑定状态与目标视图

改写后的完整代码:

struct ItemView: View {
    @State var quantityRemaining = Int.random(in: 1...10)
    let itemName: String
    // 新增状态变量控制跳转触发
    @State private var isShowingCompletionView = false
    
    var body: some View {
        NavigationStack {
            VStack {
                Text("\(itemName)")
                    .font(.title)
                    .padding()
                Spacer()
                Image(systemName: "photo")
                    .font(.system(size: 200))
                    .padding()
                Text("Quantity Remaining: \(quantityRemaining)")
                Spacer()
                Button {
                    if quantityRemaining > 0 {
                        quantityRemaining -= 1
                        // 数量归0时触发跳转
                        if quantityRemaining == 0 {
                            isShowingCompletionView = true
                        }
                    }
                } label: {
                    Text("Add one to your cart")
                }
                Spacer()
            }
            // 绑定跳转状态与目标视图
            .navigationDestination(isPresented: $isShowingCompletionView) {
                Text("You bought all the \(itemName)!")
            }
        }
    }
}

关键改动说明

  1. 移除了.background()中废弃的NavigationLink,改用NavigationStack作为视图根容器,符合SwiftUI最新导航规范
  2. 用isShowingCompletionView状态变量替代原代码中.constant(quantityRemaining == 0)的被动判断逻辑,主动控制跳转时机
  3. 在按钮点击事件中,当商品数量减至0时手动激活跳转状态,逻辑更清晰可控
  4. 通过.navigationDestination(isPresented:)绑定状态与目标视图,实现和原代码一致的自动跳转效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 07:27:06