NSTimer - 1

NSTimer 分别分基础篇和深入篇,深入篇会设计到NSRunloop所以现在先不详述,会在NSTimer - 2 篇里面学习。

基础篇也是非常好学习的,因为NSTimer提供的接口方法少而已很少理解和使用。

初始化 和 使用也是非常简单,例如:

    _hideFlowButtonTimer = [NSTimer timerWithTimeInterval:4.0f target:self selector:@selector(hideFlowButton) userInfo:nil repeats:NO];

还可以立即触发,使用方法:

- (void)fire;

防止内存泄漏,关闭计时器:

[timer invalidate];  
timer = nil;  

还可以灵活地开启 、 关闭:

//页面将要进入前台,开启定时器  
-(void)viewWillAppear:(BOOL)animated  
{  
    //开启定时器  
    [scrollView.myTimer setFireDate:[NSDate distantPast]];  
}  
  
//页面消失,进入后台不显示该页面,关闭定时器  
-(void)viewDidDisappear:(BOOL)animated  
{  
    //关闭定时器  
    [scrollView.myTimer setFireDate:[NSDate distantFuture]];  
}  

而在参考文章 Reference - 1中提到一点没有想到的计时器和函数方法相关对象(Target)里面对象的retain关系是怎么样的,详细查看Reference - 1。


这里给出一个计时器结合UIView的动画的简单实现:

在moveFlowButton初始化定时器:

- (void)moveFlowButton
{
    //洋葱头缩进到屏幕边缘定时器
    _hideFlowButtonTimer = [NSTimer timerWithTimeInterval:4.0f target:self selector:@selector(hideFlowButton) userInfo:nil repeats:NO];
    
    float durationTime = _flowButton.superview.bounds.size.width * 0.00125f ;    //动画持续时间
    
    if (_flowButton.center.x < _flowButton.superview.bounds.size.width / 2) {
        
        [UIView animateWithDuration:durationTime animations:^{
            
            _flowButton.center = CGPointMake(_flowButton.bounds.size.width / 2, _flowButton.center.y);
            _flowMenu.center = CGPointMake(_flowMenu.bounds.size.width / 2 + _flowButton.bounds.size.width, _flowMenu.center.y - 5);
            
            
        } completion:^(BOOL finished){
            [_hideFlowButtonTimer fire];
        }];
    }

}

定时器相关的方法实现:

- (void)hideFlowButton
{
    if (_flowButton.center.x < _flowButton.superview.bounds.size.width / 2) {
        [UIView animateWithDuration:0.5f animations:^{
            _flowButton.frame = CGRectMake(-_flowButton.bounds.size.width + 10, _flowButton.frame.origin.y, _flowButton.bounds.size.width, _flowButton.bounds.size.height);
        } completion:^(BOOL finished){
            _isFlowButtonDismiss = YES;
        }];
    }
}


参考文章:

Reference - 1 : 定时器的关闭和开启  :http://blog.csdn.net/enuola/article/details/8099461

Reference - 2 : 全面深入定时器 - target对象的retain值 、定时器的延时 、 与runloop的关系 : http://blog.csdn.net/enuola/article/details/9163051#comments

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值