iOS开发 使用NSTimer做循环动画

本文介绍了如何在iOS开发中使用NSTimer创建循环移动动画。通过设置NSTimer来定时触发动画,结合UIView动画块实现图片上下移动的效果。同时,文章也提及了在系统繁忙时可能存在的延迟问题以及停止动画时对NSTimer的正确处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 NSTimer是个非常非常强大的时间定时器,至于它强大到哪我也不知道。从之前使用NSTimer的情况看,NSTimer是有稍微的延时的,所以在做NSTimer与UI相关的操作时,画面可能没有想象中的流畅,最好在系统不繁忙时启用NSTimer。小朋友们下面来看点动画片

.h文件

@property(nonatomic,retain)NSTimer *timer;

@property(nonatomic,retain)UIImageView *moveImage;

.m

//timer设置

-(void)timerFire

{

     if(!self.moveImage){
                       self.moveImage = [[UIImageView alloc]initWithFrame:CGRectMake(100, 180, 120, 5)];//要做动画的小图片
    self.moveImage.image = [UIImage imageNamed:@"move.png"];
    self.moveImage.alpha = 0;//  这里置零是为了掩饰页面切换较慢时的卡顿,使小图片隐藏,之后的动画中再显示,看起来流畅。没卡顿问题的可以不设置  
    [self.view addSubview:self.moveImage];
                    }

   

    if(!self.timer){
                        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(doMove) userInfo:nil repeats:YES];
                        [self.timer fire];
                    }

}


//启动动画
-(void)doMove
{
    self.moveImage.alpha = 1;//可以不写的
    [UIView animateWithDuration:0.75 animations:^{//这里第一个动画往下移动
        self.moveImage.frame = CGRectMake(100, 380, 120, 5);//直接改center也可以改变位置
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.75 animations:^{//接着0.75秒后第二个动画往上移回原位
            self.moveImage.frame = CGRectMake(100,180, 120, 5);
        } completion:nil];
    }];
}

//停止动画

-(void)stopMove

{

  if (self.timer != nil && [self.timer isValid]) {
        [self.timer invalidate];
    }
    self.timer = nil;//这个一定要处理好,timer会对self做retain 的

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值