[英]Is there a way to add an extra function to NavigationLink? SwiftUI
I would like to add an extra function to the NavigationLink.我想为 NavigationLink 添加一个额外的功能。
example code is something like this:示例代码是这样的:
struct ContentView: View {
func yes () {
print("yes")
}
var body: some View {
NavigationView {
NavigationLink(destination: level1()) {
Text("Next")
}}}}
I know this doesn't work, but is it possible to do something like this?我知道这行不通,但是有可能做这样的事情吗? (It will go to the destination and call the function at the same time)
(它会去目的地并同时调用该函数)
NavigationLink(destination: level1(), yes()) {Text("Next")}
I tried putting a button inside the NavigationLink but it didn't work either.我尝试在 NavigationLink 中放置一个按钮,但它也不起作用。 When I do this only the function in the button works, NavigationLink doesn't.
当我这样做时,只有按钮中的功能起作用,而 NavigationLink 不起作用。
NavigationLink(destination: level1()) {
Button(action: { self.yes() })
{ Text("Button")}
}
Use the onAppear(perform:) .使用onAppear(perform:) 。 This will perform some function on a
View
's appear.这将在
View
出现时执行一些功能。
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: DetailView().onAppear {
self.someFunc()
}) {
Text("First Screen")
}
}
}
func someFunc() {
print("Click")
}
}
struct DetailView: View {
var body: some View {
Text("Second Screen")
}
}
Solution for SwiftUI, iOS 15.1 & Xcode 13.1.适用于 SwiftUI、iOS 15.1 和 Xcode 13.1 的解决方案。
import Foundation
import SwiftUI
// NavigationLink replacement with action
// Usage:
//var body: some View {
// NavigationButton(
// action: { print("tapped!") },
// destination: { Text("Pushed View") },
// label: { Text("Tap me") }
// )
//}
struct NavigationButton<Destination: View, Label: View>: View {
var action: () -> Void = { }
var destination: () -> Destination
var label: () -> Label
@State private var isActive: Bool = false
var body: some View {
Button(action: {
self.action()
self.isActive.toggle()
}) {
self.label()
.background(
ScrollView { // Fixes a bug where the navigation bar may become hidden on the pushed view
NavigationLink(destination: LazyDestination { self.destination() },
isActive: self.$isActive) { EmptyView() }
}
)
}
}
}
// This view lets us avoid instantiating our Destination before it has been pushed.
struct LazyDestination<Destination: View>: View {
var destination: () -> Destination
var body: some View {
self.destination()
}
}
I cannot find the original code, but this solution worked for me perfectly.我找不到原始代码,但这个解决方案对我来说非常有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.