iOS开发——自定义loading图的简易实现
2017-01-18 本文已影响2128人
无夜之星辰
iu-李知恩
效果:
loading.gif思路:
- 显示:在window上add自定义类型view(你的hud)。
- 隐藏:将属于这个hud类型的view从window上移除。
实现:
-
显示:
调用[CQHud show];
+ (void)show{
// 获取keyWindow
UIWindow * window = [UIApplication sharedApplication].keyWindow;
// 添加hud
CQHudView * hudView = [[CQHudView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
[hudView setBackgroundColor:[UIColor colorWithWhite:0.2 alpha:0.2]];
[window addSubview:hudView];
// 添加自定义内容(也可以封装到CQHudView里)
UIView * contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
contentView.center = CGPointMake(screenWidth/2, screenHeight/2);
[contentView setBackgroundColor:[UIColor colorWithWhite:0.2 alpha:0.8]];
contentView.layer.cornerRadius = 10;
[hudView addSubview:contentView];
UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 45, 45)];
imageView.center = CGPointMake(contentView.frame.size.width/2, 30);
imageView.image = [UIImage imageNamed:@"toast_loading"];
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView.frame), contentView.frame.size.width, 20)];
label.text = @"小主请稍候";
label.font = [UIFont systemFontOfSize:13];
label.textAlignment = NSTextAlignmentCenter;
[label setTextColor:[UIColor colorWithHexString:@"#ffffff"]];
[contentView addSubview:label];
//------- 旋转动画 -------//
CABasicAnimation *animation = [ CABasicAnimation
animationWithKeyPath: @"transform" ];
animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
// 围绕Z轴旋转,垂直与屏幕
animation.toValue = [ NSValue valueWithCATransform3D:
CATransform3DMakeRotation(M_PI, 0.0, 0.0, 1.0) ];
animation.duration = 0.5;
// 旋转效果累计,先转180度,接着再旋转180度,从而实现360旋转
animation.cumulative = YES;
animation.repeatCount = 1000;
//在图片边缘添加一个像素的透明区域,去图片锯齿
CGRect imageRrect = CGRectMake(0, 0,imageView.frame.size.width, imageView.frame.size.height);
UIGraphicsBeginImageContext(imageRrect.size);
[imageView.image drawInRect:CGRectMake(1,1,imageView.frame.size.width-2,imageView.frame.size.height-2)];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 添加动画
[imageView.layer addAnimation:animation forKey:nil];
[contentView addSubview:imageView];
}
-
隐藏:
调用[CQHud dismiss]
+ (void)dismiss{
// 遍历keyWindow上的CQHudView,一一移除
for (CQHudView * view in [UIApplication sharedApplication].keyWindow.subviews) {
if ([view isMemberOfClass:[CQHudView class]]) {
[view removeFromSuperview];
}
}
}
- 文件只有4个
注意:
- 如果想透过hud点击按钮,将hud的用户交互设为NO即可;
- 旋转loading可以用旋转动画也可以用一组图片或一张GIF图;
- loading的内容可以封装在
CQHudView
里。
优缺点:
优点自然是可以简单快速的封装好一般的loading图,但是以这种方法封装loading图的局限性也很明显。
- hud是放在整个window上而不是视图控制器上的,也就是loading图一旦出现,你的所有视图控制器上都出现loading。当我们想只给某一个视图控制器添加loading图时,此方法无效。
- 移除loading图的方法一调用就会移除所有loading。
写在最后:
这是工作之初写的loading,可以看出,当初的我想法确实很单纯,不过思路还是比较清晰。随着项目越来越大、要求越来越高,这个loading的重构也提上日程了。这里简单记录一下,顺便分享个思路。以后封装还是需先研究研究GitHub上的高点赞框架。