- 思路: 将label加在keyWindow上,创建单例利用单例属性isShowing来防止多个label叠加在keyWindow上.用GCD延迟执行使label消失的方法,再将isShowing状态改为NO->即消失状态,下次调用可以弹出.
#import "HBToast.h"
#define kScreenB [UIScreen mainScreen].bounds
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScreenW [UIScreen mainScreen].bounds.size.width
@implementation HBToast
+(instancetype)sharedTost{
static HBToast * instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [self new];
});
return instance;
}
+(void)bb_showStatus:(NSString *)status withTime:(CGFloat)time{
HBToast * toast = [HBToast sharedTost];
if (!toast.isShowing) {
toast.isShowing = YES;
UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
UILabel * lbl = [UILabel new];
lbl.text = status;
lbl.backgroundColor = [UIColor blackColor];
lbl.alpha = 0.7;
lbl.layer.cornerRadius = 3.0;
lbl.layer.masksToBounds = YES;
lbl.textColor = [UIColor whiteColor];
lbl.font = [UIFont systemFontOfSize:16];
lbl.textAlignment = NSTextAlignmentCenter;
CGFloat lblH = 27;
CGFloat lblW = 150;
CGFloat lblY = kScreenH - lblH - 60;
CGFloat lblX = (kScreenW - lblW) * 0.5;
lbl.frame = CGRectMake(lblX, lblY, lblW, lblH);
[keyWindow addSubview:lbl];
NSLog(@"显示");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"隐藏");
toast.isShowing = NO;
[lbl removeFromSuperview];
});
}
}
+(void)bb_showStatus:(NSString *)status{
HBToast * toast = [HBToast sharedTost];
if (!toast.isShowing) {
toast.isShowing = YES;
UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
UILabel * lbl = [UILabel new];
lbl.text = status;
lbl.backgroundColor = [UIColor blackColor];
lbl.alpha = 0.7;
lbl.layer.cornerRadius = 3.0;
lbl.layer.masksToBounds = YES;
lbl.textColor = [UIColor whiteColor];
lbl.font = [UIFont systemFontOfSize:16];
lbl.textAlignment = NSTextAlignmentCenter;
CGFloat lblH = 27;
CGFloat lblW = 150;
CGFloat lblY = kScreenH - lblH - 60;
CGFloat lblX = (kScreenW - lblW) * 0.5;
lbl.frame = CGRectMake(lblX, lblY, lblW, lblH);
[keyWindow addSubview:lbl];
NSLog(@"显示");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"隐藏");
toast.isShowing = NO;
[lbl removeFromSuperview];
});
}
}
@end