UITimer 是 iOS 系統(tǒng)中的定時器。
今天主要實現(xiàn)的功能點 開始/停止 定時器,給定時器刷新函數(shù)帶入?yún)?shù)和如何通過定時器更改 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 每隔多久調(diào)用定時器,以秒為單位
// P2 實現(xiàn)定時器函數(shù)的對象
// P3 定時器函數(shù)對象
// P4 可以定時器函數(shù)中的一個參數(shù),可以傳 nil
// P5 是否重復(fù)
_timerView = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer:) userInfo:@"DaveZ" repeats:YES];
}
- (void) pressStop {
if (_timerView != nil) {
[_timerView invalidate];
}
}
// 可以將定時器本身作為參數(shù)傳入
- (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