gpt4 book ai didi

iphone - 在全局范围内使用 MBProgressHUD + 使其成为单例

转载 作者:IT王子 更新时间:2023-10-29 07:58:18 25 4
gpt4 key购买 nike

在我的项目中,每个用户交互事件都会进行一次网络调用(这是 TCP,而不是 HTTP)。我需要 Activity Indicator 是全局的,以便从随机 UIViewController显示并从 NetworkActivityManager 类(自定义类)中隐藏处理网络事件,它不是 UIViewController 或 UIView 的子类)。

在网上搜索后,我发现 MBProgressHUD 用于相同的目的,但我无法找到有关如何在全局范围内使用它的示例。 (我所说的全局是指 MBProgressHUD 的单例对象和显示和隐藏它的类方法。)

以下是我尝试过的方法,但失败了:在 AppDelegate.h 中:

@property (nonatomic, retain) MBProgressHUD *hud;

AppDelegate.m 中:

@synthesize hud;

在一些随机的 UIViewController 对象中:

appDelegate.hud = [MBProgressHUD showHUDAddedTo:appDelegate.navigationController.topViewController.view animated:YES];
appDelegate.hud.labelText = @"This will take some time.";

在隐藏它的同时,从 NetworkActivityManager 类:

[MBProgressHUD hideHUDForView:appDelegate.navigationController.topViewController.view animated:YES];

这会使项目在一段时间后崩溃(由于内存问题。)我在我的项目中使用 ARC,而且我使用的是 MBProgressHUD 的 ARC 版本。

我错过了什么吗?

重要问题:

我可以让 MBProgressHUD 像 UIAlertView 一样工作吗? (也就是说,我的意思是 MBProgressHUD 的实现独立于 UIView——它使用 showHUDAddedTo: 来展示自己)???

请注意:在上面隐藏 MBProgressHUD 的代码中,View 可能与显示 MBProgressHUD 时的 View 不同。

非常感谢任何帮助。

最佳答案

您可以将其添加到您喜欢的类别中:

+ (MBProgressHUD *)showGlobalProgressHUDWithTitle:(NSString *)title {
UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
hud.labelText = title;
return hud;
}

+ (void)dismissGlobalHUD {
UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
[MBProgressHUD hideHUDForView:window animated:YES];
}

这可以在任何类上调用。使用这些类便利方法时,您无需保留对 HUD 的强引用。

根据您的具体情况,您可能还希望处理在隐藏另一个 HUD 之前请求新 HUD 的情况。您可以在新的 HUD 出现时隐藏之前的 HUD,或者想出某种排队等。

在显示新 HUD 实例之前隐藏之前的 HUD 实例非常简单。

+ (MBProgressHUD *)showGlobalProgressHUDWithTitle:(NSString *)title {
UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
[MBProgressHUD hideAllHUDsForView:window animated:YES];
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
hud.labelText = title;
return hud;
}

关于iphone - 在全局范围内使用 MBProgressHUD + 使其成为单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12033080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com