代码如下:
//
//
// Created by Bigun on 2019/7/2.
// Copyright © 2019 Enjoy. All rights reserved.
//
#import "HNToastView.h"
@implementation HNToastView
+(void)toast:(NSString*)text{
if (![text length]){
text = @"发生未知错误";
}
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
// 延时1s执行toast
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
UILabel *_label = [[UILabel alloc] init];
_label.text = text;
_label.tag = 1001;
_label.textAlignment = NSTextAlignmentCenter;
_label.layer.cornerRadius = 18.f;
_label.font = [UIFont systemFontOfSize:14];
_label.layer.masksToBounds = YES;
// 根据字体得到NSString的尺寸
CGSize size = [_label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:_label.font,NSFontAttributeName,nil]];
_label.frame = CGRectMake(100,100, size.width,size.height);
_label.textColor = [UIColor whiteColor];
_label.backgroundColor = [UIColor blackColor];
_label.alpha = 0.8;
_label.translatesAutoresizingMaskIntoConstraints = NO;
[[UIApplication sharedApplication].keyWindow addSubview:_label];
[_label mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(size.width+50, size.height+20));
make.centerX.equalTo(_label.superview);
make.bottom.equalTo(_label.superview).offset(-150);
}];
[UIView animateWithDuration:3 animations:^{
_label.alpha = 0;
}];
});
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
UIView *view = [self getViewByTag:1001 andParentView:[UIApplication sharedApplication].keyWindow];
if (view){
[view removeFromSuperview];
view = nil;
}
}
-(UIView*)getViewByTag:(int)tag andParentView:(UIView*)parentView{
for (UIView *findView in parentView.subviews){
if (findView.tag == tag){
return findView;
}
}
return nil;
}
@end
调用方法
[HNToastView toast:@"xxx"];