SwiftUI:更新Environment Object不重绘视图+解决重复跳转登录页问题
SwiftUI启动页倒计时多次跳转登录页问题及Environment Object优化方案
一、解决启动页多次跳转登录页的问题
问题根源:TimerView中的timer是存储属性,当SpashScreen因router的@Published属性更新而重绘时,TimerView会被重新初始化,创建新的Timer实例,导致多个Timer同时运行,倒计时结束后多次触发跳转回调。
修复方案:
- 将Timer改为@State属性,确保视图生命周期内唯一实例
- 添加状态标记防止重复执行跳转回调
修改后的TimerView代码:
struct TimerView: View { @State private var countDown = 5 @State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() @State private var hasNavigated = false // 标记是否已完成跳转 var callBack: (() -> Void) var body: some View { VStack { if let url = Bundle.main.url(forResource: "provider_splash", withExtension: "gif") { KFAnimatedImage(url) .scaledToFill() .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) .ignoresSafeArea(.all) } } .onReceive(timer) { _ in guard !hasNavigated else { return } // 已跳转则直接返回 if countDown > 0 { countDown -= 1 } else { timer.upstream.connect().cancel() hasNavigated = true // 标记为已跳转 callBack() } } .onDisappear { timer.upstream.connect().cancel() // 视图消失时取消Timer,避免内存泄漏 } } }
二、不重绘整个视图的情况下更新Environment Object
SwiftUI的视图重绘由依赖追踪驱动,只要视图依赖的@Published属性变化,视图就会重绘。要减少不必要的重绘,可以从以下几个方向优化:
1. 拆分视图,隔离依赖
将视图拆分为多个子视图,只有实际需要访问Environment Object属性的子视图才会在属性变化时重绘,其他子视图不受影响。
示例:把启动页的内容拆成独立子视图
struct SplashContentView: View { var body: some View { if let url = Bundle.main.url(forResource: "provider_splash", withExtension: "gif") { KFAnimatedImage(url) .scaledToFill() .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) .ignoresSafeArea(.all) } } } // 在TimerView中使用该子视图 struct TimerView: View { // ... 其他属性和逻辑不变 var body: some View { SplashContentView() .onReceive(timer) { _ in // ... 跳转逻辑不变 } } }
SplashContentView不依赖任何ObservableObject,即使TimerView重绘,它也不会被重新创建(除非自身属性变化)。
2. 使用EquatableView控制重绘
让视图遵循Equatable协议,然后用EquatableView包裹,只有当视图的Equatable条件满足时才会重绘。
示例:
struct SplashContentView: View, Equatable { static func == (lhs: SplashContentView, rhs: SplashContentView) -> Bool { // 视图无可变属性,直接返回true,永远不重绘 return true } var body: some View { // ... 内容不变 } } // 使用时 EquatableView(content: SplashContentView())
3. 细化ObservableObject的@Published属性
避免在Router中使用单一的navPath大对象,拆分出更细粒度的@Published属性,只在必要时更新。不过在路由场景中,navPath是核心依赖,但可以确保只有真正需要监听navPath的视图才会依赖它,减少不必要的重绘范围。
内容的提问来源于stack exchange,提问作者bhavesh chaudhari
相关产品推荐
相关产品推荐

