IOS-UITimer的使用

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,232评论 4 61
  • 现在的年轻人都在想些什么?我真是不懂了。大概我们真的老了。 那天去快递公司寄快递,填单子的时候,听见几个小姑娘的对...
    慕容小秋阅读 544评论 0 0
  • 一、 人的一生何其短暂 从黑发到白发,仿佛就一瞬间的事儿 到最后,带不走任何东西 唯有那些刻骨铭心的记忆 在最后一...
    许17阅读 428评论 2 7