IOS-UITimer的使用

2017-10-15  本文已影响0人  DaveZ

UITimer 是 iOS 系统中的定时器。

今天主要实现的功能点 开始/停止 定时器,给定时器刷新函数带入参数和如何通过定时器更改 View 的位置属性,从而得到 View 的动画效果。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

{
    // 定义一个定时器
    NSTimer* _timerView;
}

@property (retain, nonatomic) NSTimer* timerView;

@end

接着我们在 ViewController.m 编写如下代码

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

// 属性和成员变量的同步
@synthesize timerView = _timerView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(100, 100, 80, 40);
    [btn setTitle:@"开始定时器" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton* btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn1.frame = CGRectMake(100, 200, 80, 40);
    [btn1 setTitle:@"停止定时器" forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn1];

    UIView* view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, 50, 50);
    view.backgroundColor = [UIColor greenColor];
    view.tag = 200;
    [self.view addSubview:view];
}

- (void) pressStart {
    // P1 每隔多久调用定时器,以秒为单位
    // P2 实现定时器函数的对象
    // P3 定时器函数对象
    // P4 可以定时器函数中的一个参数,可以传 nil
    // P5 是否重复
    _timerView = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer:) userInfo:@"DaveZ" repeats:YES];
    
    
}

- (void) pressStop {
    if (_timerView != nil) {
        [_timerView invalidate];
    }
}

// 可以将定时器本身作为参数传入
- (void) updateTimer: (NSTimer*) timer {
    NSLog(@"TEST name = %@", timer.userInfo);
    
    UIView* view = [self.view viewWithTag:200];
    view.frame = CGRectMake(view.frame.origin.x + 1, view.frame.origin.y + 1, 50, 50);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
上一篇 下一篇

猜你喜欢

热点阅读