从后台回到前台时SVProgressHUD动画失效问题求助
解决SVProgressHUD后台返回前台动画停止的问题
我之前开发时也碰到过一模一样的情况——应用后台停留5秒以上再切回前台,SVProgressHUD就只显示静态的加载圈,完全不播放旋转动画了。试了几个可行的解决方法,分享给你:
监听前后台通知,回到前台时重置HUD
iOS在后台会暂停绝大多数动画,回到前台后不会自动恢复。我们可以监听UIApplicationWillEnterForegroundNotification通知,当应用回到前台时,如果HUD还处于显示状态,就先隐藏再重新显示,强制触发动画逻辑:Objective-C代码示例:
// 在AppDelegate的启动方法里注册通知 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restartHUDAnimation) name:UIApplicationWillEnterForegroundNotification object:nil]; return YES; } - (void)restartHUDAnimation { if ([SVProgressHUD isVisible]) { // 先保存当前的状态文本和遮罩类型,避免重新显示时样式不一致 NSString *currentStatus = [SVProgressHUD status]; SVProgressHUDMaskType maskType = [SVProgressHUD maskType]; [SVProgressHUD dismiss]; [SVProgressHUD showWithStatus:currentStatus maskType:maskType]; } }Swift代码示例:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { NotificationCenter.default.addObserver(self, selector: #selector(restartHUDAnimation), name: UIApplication.willEnterForegroundNotification, object: nil) return true } @objc func restartHUDAnimation() { guard SVProgressHUD.isVisible() else { return } let currentStatus = SVProgressHUD.status() let maskType = SVProgressHUD.maskType() SVProgressHUD.dismiss() SVProgressHUD.show(withStatus: currentStatus, maskType: maskType) }修改SVProgressHUD源码,让动画自动恢复
如果不想做外部监听,可以直接修改SVProgressHUD的内部逻辑。找到负责旋转动画的代码块(一般在SVProgressHUD.m的圆形进度层相关方法里),添加响应前台通知的逻辑,回到前台时重新启动动画:// 在SVProgressHUD类中添加 - (void)setupForegroundNotificationObserver { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resumeRotationAnimation) name:UIApplicationWillEnterForegroundNotification object:nil]; } - (void)resumeRotationAnimation { if (self.isVisible) { // 清除旧动画,重新初始化旋转逻辑 [self.circularProgressLayer removeAllAnimations]; [self setupCircularProgressLayer]; // 这个方法是原代码中初始化旋转动画的方法 } }记得在HUD的初始化方法里调用
setupForegroundNotificationObserver完成注册。尝试升级到最新版SVProgressHUD
这个问题可能是旧版本的已知bug,作者后续说不定已经修复了。去替换成GitHub上的最新版本代码,大概率能直接解决问题。
内容的提问来源于stack exchange,提问作者Ramakrishna
相关产品推荐
相关产品推荐

