自定义loading
.h文件中有两个类方法,显示以及移除
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface LCSLoading : UIView
+ (void)showInView:(UIView *)parentView;
+ (void)dismissFromView:(UIView *)parentView;
@end
NS_ASSUME_NONNULL_END
.m里是方法的实现
@implementation LCSLoading
+ (void)showInView:(UIView *)parentView {
CGFloat parentWidth = parentView.frame.size.width;
CGFloat parentHeight = parentView.frame.size.height;
//防止多个loading叠加在一起
for (LCSLoading *view in parentView.subviews) {
if([view isMemberOfClass:[LCSLoading class]]) return;
}
//创建hud
LCSLoading *hudView = [[LCSLoading alloc] initWithFrame:CGRectMake(0, 0, parentWidth, parentHeight)];
[hudView setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0.1]];
[parentView addSubview:hudView];
//添加旋转图片背景
CGFloat contentWidth = 80, contentHeight = 80;
UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, contentWidth, contentHeight)];
[contentView setBackgroundColor:[UIColor colorWithWhite:0.2 alpha:0.8]];
contentView.center = CGPointMake(parentWidth/2, parentHeight/2);
contentView.layer.cornerRadius = 10;
[hudView addSubview:contentView];
//添加旋转图片
UIImageView *loadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
loadingImageView.center = CGPointMake(contentView.frame.size.width/2, contentView.frame.size.height/2);
loadingImageView.image = [UIImage imageNamed:@"punch_loading"];
[contentView addSubview:loadingImageView];
//添加旋转动画
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI, 0.0, 0.0, 1.0)];
animation.toValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
animation.duration = 1;
animation.cumulative = YES;
animation.repeatCount = MAXFLOAT;
//在图片边缘添加透明区域,去掉图片锯齿
CGRect imageRect = CGRectMake(0, 0, loadingImageView.frame.size.width, loadingImageView.frame.size.height);
UIGraphicsBeginImageContext(imageRect.size);
[loadingImageView.image drawInRect:CGRectMake(1, 1, loadingImageView.frame.size.width-2, loadingImageView.frame.size.height-2)];
loadingImageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//给图片添加动画
[loadingImageView.layer addAnimation:animation forKey:nil];
}
+ (void)dismissFromView:(UIView *)parentView {
for (LCSLoading *view in parentView.subviews) {
if([view isMemberOfClass:[LCSLoading class]]) {
[UIView animateWithDuration:0.5 animations:^{
view.alpha = 0.01;
} completion:^(BOOL finished) {
[view removeFromSuperview];
}];
}
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
接下来是具体调用,显示后5s移除
[LCSLoading showInView:self.view];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[LCSLoading dismissFromView:self.view];
});