导航链接 - Swift UI iOS 16
#ios #swift #swiftui #xcode

曾经在导航视图中使用导航链接,并在xcode中获得此折旧警告?

Xcode deprecation warning - 'init(destination:isActive:label:)' was deprecated in iOS 16.0: use NavigationLink(value🏷️) inside a NavigationStack or NavigationSplitView

这是修复它的方法!

让我们从带有.stack navigationViewStyle的NavigationView的ios15示例开始,然后在按下按钮时链接到SecondView的导航链接。

import SwiftUI

struct ContentView: View {
    @State var showSecondView: Bool = false
    var body: some View {
        NavigationView {
            VStack {
                Button {
                    showSecondView.toggle()
                } label: {
                    Text("Show Second View")
                }
                NavigationLink(
                    destination: SecondView(),
                    isActive: $showSecondView
                ) {
                    EmptyView()
                }
            }
        }
        .navigationViewStyle(.stack)
    }
}

struct SecondView: View {
    var body: some View {
        VStack {
            Text("Hello! I'm the second View")
        }
    }
}

要更新iOS 16并删除弃用警告我们可以:

  • NavigationView更改为NavigationStack
  • NavigationLink更改为navigationDestination
  • 删除.navigationViewStyle(.stack)
struct ContentView: View {
    @State var showSecondView: Bool = false
    var body: some View {
        NavigationStack {
            VStack {
                Button {
                    showSecondView.toggle()
                } label: {
                    Text("Show Second View")
                }
                .navigationDestination(
                 isPresented: $showSecondView) {
                     SecondView()
                 }
            }
        }
    }
}

希望能帮助其他遇到同样警告的人!