如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图
Posted
技术标签:
【中文标题】如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图【英文标题】:How to navigate another view in onReceive timer closure SwiftUI iOS 【发布时间】:2020-08-03 23:58:32 【问题描述】:我正在尝试在计时器达到特定时间时导航到另一个视图。例如,我想在 5 分钟后导航到另一个视图。在 swift 中,我可以轻松实现这一点,但我是 SwiftUI 的新手,我们将不胜感激。
我的代码:
struct TwitterWebView: View
@State var timerTime : Float
@State var minute: Float = 0.0
@State private var showLinkTarget = false
let timer = Timer.publish(every: 60.0, on: .main, in: .common).autoconnect()
var body: some View
WebView(url: "https://twitter.com/")
.navigationBarTitle("")
.navigationBarHidden(true)
.onReceive(timer) _ in
if self.minute == self.timerTime
print("Timer completed navigate to Break view")
NavigationLink(destination: BreakView())
Text("Test")
self.timer.upstream.connect().cancel()
else
self.minute += 1.0
【问题讨论】:
【参考方案1】:这是可能的方法(当然假设 TwitterWebView
在父母的某处有 NavigationView
)
struct TwitterWebView: View
@State var timerTime : Float
@State var minute: Float = 0.0
@State private var showLinkTarget = false
let timer = Timer.publish(every: 60.0, on: .main, in: .common).autoconnect()
@State private var shouldNavigate = false
var body: some View
WebView(url: "https://twitter.com/")
.navigationBarTitle("")
.navigationBarHidden(true)
.background(
NavigationLink(destination: BreakView(),
isActive: $shouldNavigate) EmptyView()
)
.onReceive(timer) _ in
if self.minute == self.timerTime
print("Timer completed navigate to Break view")
self.timer.upstream.connect().cancel()
self.shouldNavigate = true // << here
else
self.minute += 1.0
【讨论】:
以上是关于如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Apple Watch(iOS)上创建秒表(计时器)[关闭]
使用Xcode / Swift或独角兽精灵灰尘在iPad上覆盖(阻止)或关闭iOS
如果我关闭活动,从 BroadcastReceiver.onReceive 调用 peekService 将返回 null