在我们app开发中,经常要用到加载动画,写了个加载动画,封装在AXLoadingAnimationView类中,主要的代码如下。
UI初始化代码
-(void)setupUI
{
UIView *leftView = [[UIView alloc] init];
leftView.backgroundColor = [UIColor redColor];
self.leftBallView = leftView;
[self addSubview:leftView];
UIView *middleView = [[UIView alloc]init];
middleView.backgroundColor = [UIColor blackColor];
self.middleBallView = middleView;
[self addSubview:middleView];
UIView *rightView = [[UIView alloc]init];
rightView.backgroundColor = [UIColor blueColor];
self.rightBallView = rightView;
[self addSubview:rightView];
self.middleBallView.frame = CGRectMake(0, 0, self.ballSize, self.ballSize);
self.leftBallView.frame = CGRectMake(0, 0, self.ballSize, self.ballSize);
self.rightBallView.frame = CGRectMake(0, 0, self.ballSize, self.ballSize);
self.middleBallView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);//self.center;
self.leftBallView.center = CGPointMake(self.middleBallView.center.x - self.ballSize*2, self.middleBallView.center.y);
self.rightBallView.center = CGPointMake(self.middleBallView.center.x + self.ballSize*2, self.middleBallView.center.y);
[self setCornerWithView:self.leftBallView borderColor:[UIColor clearColor] borderWidth:1 cornerRadius:self.ballSize/2];
[self setCornerWithView:self.middleBallView borderColor:[UIColor clearColor] borderWidth:1 cornerRadius:self.ballSize/2];
[self setCornerWithView:self.rightBallView borderColor:[UIColor clearColor] borderWidth:1 cornerRadius:self.ballSize/2];
}
当我们的视图添加到父视图或者从父视图移除会调用如下函数,可以看到当添加到父视图时开始动画,当从父视图移除时,停止动画。
-(void)didMoveToSuperview
{
if (self.superview) {
[self startAnimation];
}
else
{
[self stopAnimation];
}
}
开始动画
-(void)startAnimation
{
self.readyStop = NO;
self.isAnimation = YES;
[self performAnimation];
}
执行动画performAnimation函数代码如下:
-(void)performAnimation
{
[UIView animateWithDuration:0.3 animations:^{
self.leftBallView.centerX = self.leftBallView.centerX + self.ballSize*2;
self.rightBallView.centerX = self.rightBallView.centerX - self.ballSize*2;
self.leftBallView.alpha = 0.5;
self.rightBallView.alpha = 0.5;
} completion:^(BOOL finished) {
UIColor *cr = self.leftBallView.backgroundColor;
self.leftBallView.backgroundColor = self.middleBallView.backgroundColor;
self.middleBallView.backgroundColor = cr;
[UIView animateWithDuration:0.3 animations:^{
self.leftBallView.alpha = 0.5;
self.rightBallView.alpha = 0.5;
self.leftBallView.centerX = self.leftBallView.centerX + self.ballSize*2;
self.rightBallView.centerX = self.rightBallView.centerX - self.ballSize*2;
} completion:^(BOOL finished) {
UIView *vw = self.leftBallView;
self.leftBallView = self.rightBallView;
self.rightBallView = vw;
if (!self.readyStop) {
[self performAnimation];
}
}];
}];
}
具体代码上传到github:https://github.com/jiangtaidi/LoadingAnimationView.git