Swiftui NavigationView定时器延迟



在我的应用程序中,我导航到一个页面(例如,页面2),然后希望在页面上显示动画(而不是其他),然后使用NavigationView执行并移动到一个新视图。换句话说,我希望NavigationView目标视图在延迟计时器(比如3秒)之后加载,而不需要用户点击按钮。在这3秒内,动画将运行。动画和NavigationView本身工作得很好,但我目前的解决方案要求用户单击按钮/文本以移动到目标视图,这有点笨拙。我到处都找不到解决办法。任何帮助都将非常感激。谢谢!

应该可以:

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
}
}
}
}

或者:

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
}
}
}
}

您可以使用DelayedNavigationLink,参见下面的实现。使用例子:

var body: some View {
VStack {
Text("Navigation link will run in 3 seconds")
DelayedNavigationLink(delay: .seconds(3)) {
Text("Destination view")
}
}
}

实现:

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
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新