序言
在项目中,我们要给一些用户的友好提示,比如正确提示,错误提示,警告提示,正在加载中的提示,所以封装好一个信息提示的工具类可以起到事半功倍的效果。
效果如下所示
![](https://img.haomeiwen.com/i1653926/db1839ed8702b69c.gif)
解析
该 工具类主要是基于MBProgressHUD 的基础上进行二次封装,对外提供了很多方法,外界直接根据需要,调用对应的方法即可,方便实用。
对外接口
/**
备注:
1. 调用 ok,error,warning 方法时,进行信息提示,有对应图片,当时间到后,会自动消失,并且不管是否有传 toView 参数,在显示的同时还是可以进行交互的.即可以重复点击
2. 调用 message 方法,只进行信息展示,没有对应图片.当时间到后,会自动消失,并且不管是否有传 toView 参数,在显示的同时还是可以进行交互的.即可以重复点击
3. 调用 info 方法,显示一个 loading 视图,不会自动消失,需要外界调用对应方法让其消失,并且在展示的时候禁止用户进行其他交互.所以这里添加的图层需要注意,根据需求添加图层
*/
@interface AlertUtils : NSObject
// 成功提示 - 会自动消失
+ (void)success:(NSString *)msg;
+ (void)success:(NSString *)msg duration:(int)duration;
+ (void)success:(NSString *)msg duration:(int)duration toView:(UIView *)toView;
// 错误提示 - 会自动消失
+ (void)error:(NSString *)msg;
+ (void)error:(NSString *)msg duration:(int)duration;
+ (void)error:(NSString *)msg duration:(int)duration toView:(UIView *)toView;
// 警告提示 - 会自动消失
+ (void)warning:(NSString *)msg;
+ (void)warning:(NSString *)msg duration:(int)duration;
+ (void)warning:(NSString *)msg duration:(int)duration toView:(UIView *)toView;
// 信息提示,没有图片
+ (void)message:(NSString *)msg;
+ (void)message:(NSString *)msg duration:(int)duration;
+ (void)message:(NSString *)msg duration:(int)duration toView:(UIView *)toView;
// 转菊花的提示 - 不会自动消失
+ (MBProgressHUD *)info:(NSString *)msg;
+ (MBProgressHUD *)info:(NSString *)msg toView:(UIView *)toView;
+ (MBProgressHUD *)showTopWinMessage:(NSString *)msg duration:(int)duration;
内部核心实现方法
// 会自动消失
+ (void)bgShowMessage:(NSString *)msg duration:(int)dura toView:(UIView *)toView icon:(NSString *)icon {
if (![msg isKindOfClass:[NSString class]] || msg == nil || msg.length == 0) {
return;
}
if (![NSThread isMainThread]) {
return;
}
if (dura == 0) {
dura = msg.length / kReadEverySecond;
}
// 设置停留时间
dura = dura < 1.5 ? 1.5 : dura;
dura = dura > 5 ? 5 : dura;
MBProgressHUD *hud;
if (toView == nil) {
AppDelegate *appDelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
hud = [MBProgressHUD showHUDAddedTo:appDelegate.window animated:YES];
} else {
hud = [MBProgressHUD showHUDAddedTo:toView animated:YES];
}
hud.margin = 15;
hud.label.numberOfLines = 0;
hud.label.text = msg;
hud.label.font = [UIFont systemFontOfSize:14];
if (icon != nil) {
NSString *iconName = [NSString stringWithFormat:@"MBProgressHUD.bundle/%@",icon];
hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:iconName]];
hud.mode = MBProgressHUDModeCustomView;
} else {
hud.mode = MBProgressHUDModeText;
}
hud.removeFromSuperViewOnHide = true;
hud.contentColor = [UIColor whiteColor];
hud.bezelView.color = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
hud.userInteractionEnabled = NO; // 即在展示的同时,用户还可以点击其他区域进行交互
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, dura * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[hud hideAnimated:YES];
});
}
如有不足,欢迎指正。生活源于创造,技术源于分享。
网友评论