在我們app開發(fā)中珠十,經(jīng)常要用到加載動畫疼邀,寫了個(gè)加載動畫誓焦,封裝在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];
}
當(dāng)我們的視圖添加到父視圖或者從父視圖移除會調(diào)用如下函數(shù),可以看到當(dāng)添加到父視圖時(shí)開始動畫吴叶,當(dāng)從父視圖移除時(shí),停止動畫序臂。
-(void)didMoveToSuperview
{
if (self.superview) {
[self startAnimation];
}
else
{
[self stopAnimation];
}
}
開始動畫
-(void)startAnimation
{
self.readyStop = NO;
self.isAnimation = YES;
[self performAnimation];
}
執(zhí)行動畫performAnimation函數(shù)代碼如下:
-(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