美文网首页
iOS - 定时器

iOS - 定时器

作者: 小黑Unity_齐xc | 来源:发表于2019-01-18 19:56 被阅读5次

    头文件

    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController{
        //头文件里定义计时器
        NSTimer* _timer;
    }
    
    //定义定时器属性
    //retain 对NSObject对象复制
    //nonatomic 单线程
    @property(retain, nonatomic)NSTimer* timer;
    @end
    

    源文件

    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    //属性与成员变量的映射/综合/同步
    @synthesize timer = _timer;
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        UIButton* btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn1.frame = CGRectMake(100, 100, 100, 100);
        [btn1 setTitle:@"start timer" forState:UIControlStateNormal];
        [btn1 addTarget:self action:@selector(btn1Click) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn1];
        
        UIButton* btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn2.frame = CGRectMake(100, 220, 100, 100);
        [btn2 setTitle:@"end timer" forState:UIControlStateNormal];
        [btn2 addTarget:self action:@selector(btn2Click) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn2];
        
        [self initView];
    }
    
    -(void) initView{
        UIView* view = [[UIView alloc]init];
        view.frame = CGRectMake(0, 0, 50, 50);
        view.tag = 111;
        [view setBackgroundColor:[UIColor orangeColor]];
        [self.view addSubview:view];
        
    }
    
    -(void) btn1Click{
        NSLog(@"btn1Click");
        
        //通过NSTimer的类方法创建一个定时器
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer:) userInfo:@"计时" repeats:YES];
    }
    
    int i = 0;
    -(void) onTimer:(NSTimer*)timer{
        NSLog(@"onTimer %@ %d", timer.userInfo, i);
        i+=1;
        
        //UIView* view = [self.view viewWithTag:111];
        //view.frame = CGRectMake(view.frame.origin.x + 10, view.frame.origin.y +0.1f, 50, 50);
    }
    
    -(void) btn2Click{
        NSLog(@"btn2Click");
        if(_timer!=NULL){
            [_timer invalidate];
        }
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    
    @end
    

    相关文章

      网友评论

          本文标题:iOS - 定时器

          本文链接:https://www.haomeiwen.com/subject/rjqodqtx.html