[英]Swiftui NavigationView timer delay
In my app I navigate to a page (say, page 2), then wish to show an animation (and nothing else) on the page, before executing and moving to a new view using NavigationView.在我的应用程序中,我导航到一个页面(例如第 2 页),然后希望在页面上显示 animation(仅此而已),然后使用 NavigationView 执行并移动到新视图。 In other words, I'd like the NavigationView destination view to load after a delay timer (say 3 seconds), without the user having to click a button.换句话说,我希望 NavigationView 目标视图在延迟计时器(比如 3 秒)后加载,而无需用户单击按钮。 During that 3 seconds, the animation will be running.在这 3 秒内,animation 将运行。 The animation and the NavigationView work fine on their own, but my current solution requires the user to click a button/text to move to the destination view, which is a little clunky. animation 和 NavigationView 可以自己正常工作,但我当前的解决方案需要用户单击按钮/文本才能移动到目标视图,这有点笨拙。 I can't find a solution anywhere.我在任何地方都找不到解决方案。 Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks!谢谢!
This should work:这应该有效:
struct MyView: View {
@State var pushNewView: Bool = false
var body: some View {
NavigationView {
NavigationLink(isActive: $pushNewView) {
Text("Second View")
} label: {
Text("First View") //Replace with some animation content
}
}
.onAppear {
Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { _ in
pushNewView = true
}
}
}
}
Alternatively:或者:
struct MyView: View {
@State var pushNewView: Bool = false
var body: some View {
NavigationView {
NavigationLink(isActive: $pushNewView) {
Text("Second View")
} label: {
Text("First View") //Replace with some animation content
}
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
pushNewView = true
}
}
}
}
You can use DelayedNavigationLink
, see implementation below.您可以使用DelayedNavigationLink
,请参阅下面的实现。 Usage example:使用示例:
var body: some View {
VStack {
Text("Navigation link will run in 3 seconds")
DelayedNavigationLink(delay: .seconds(3)) {
Text("Destination view")
}
}
}
Implementation:执行:
struct DelayedNavigationLink<Destination: View, Label: View>: View {
@State private var linkIsActive = false
private let delay: DispatchTimeInterval
private var destination: () -> Destination
private var label: () -> Label
init(delay: DispatchTimeInterval, destination: @escaping () -> Destination) where Label == EmptyView {
self.init(delay: delay, destination: destination, label: EmptyView.init)
}
init(delay: DispatchTimeInterval, destination: @escaping () -> Destination, label: @escaping () -> Label) {
self.delay = delay
self.destination = destination
self.label = label
}
var body: some View {
NavigationLink(isActive: $linkIsActive, destination: destination, label: label)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
linkIsActive = true
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.