[英]How to replace init(destination:tag:selection:label:) with NavigationLink(value:label:) in Swift for iOS16?
I am using the following Swift code to do 2 things in my iPhone app:我正在使用以下 Swift 代码在我的 iPhone 应用程序中做两件事:
somethingElse()
when button is clicked单击按钮时调用方法somethingElse()
SecondView()
将视图更改为SecondView()
Code代码
struct PrimaryView: View {
@State var buttonSelected: Int? = nil
func onSubmit() {
somethingElse()
self.buttonSelected = 1
}
var body: some View {
NavigationStack {
NavigationLink(destination: SecondView(), tag: 1, selection: $buttonSelected) {
Button(action: {
onSubmit()
}) {
Text("Click me")
}
}
}
}
}
This works fine but I get the following warning:这工作正常,但我收到以下警告:
'init(destination:tag:selection:label:)' was deprecated in iOS 16.0: use NavigationLink(value:label:) inside a List within a NavigationStack or NavigationSplitView... 'init(destination:tag:selection:label:)' 在 iOS 16.0 中被弃用:在 NavigationStack 或 NavigationSplitView 的列表中使用 NavigationLink(value:label:)...
Question: How do I refactor this code so the warning goes away but the functionality stays the same?问题:如何重构此代码以使警告消失但功能保持不变?
If you follow the advice on the warning, you'd get something like this:如果您按照警告中的建议进行操作,您会得到如下信息:
NavigationStack {
List {
NavigationLink(value: 1) { // use some tag here
Button(action: {
onSubmit()
}) {
Text("Click me")
}
}
}.navigationDestination(for: Int.self) { _ in
// check the closure parameter here to return a different view
SecondView()
}
}
Of course, this will give you a List
instead.当然,这会给你一个List
。 If you don't want that, the other overload, destinationLink(isPresented:destination:)
, seems to work.如果您不希望这样,另一个重载destinationLink(isPresented:destination:)
似乎可以工作。 The code is simply代码很简单
NavigationStack {
Button(action: {
onSubmit()
}) {
Text("Click me")
}.navigationDestination(isPresented: $buttonSelected, destination: { SecondView() })
}
With buttonSelected
changed to a Bool
:随着buttonSelected
更改为Bool
:
@State var buttonSelected: Bool = false
func somethingElse() {
print("something Else")
}
func onSubmit() {
somethingElse()
self.buttonSelected = true
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.