1.定义定时器属性
#import <UIKit/UIKit.h>
@interface SearchController : UIViewController{
}
@property(retain,nonatomic) NSTimer* nsTime;
@end
2.视图添加启动定时器按钮
- (void)viewDidLoad {
[super viewDidLoad];
UIButton * start = [UIButton buttonWithType:UIButtonTypeSystem];
start.frame =CGRectMake(100, 100, 100, 40);
[start setTitle:@"启动定时器" forState:UIControlStateNormal];
start.backgroundColor = [UIColor greenColor];
[start addTarget:self action:@selector(startTimer) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:start];
//创建一个view视图
UITextView * txt =[[UITextView alloc]init];
txt.frame =CGRectMake(20, 20, 80, 80);
txt.backgroundColor=[UIColor orangeColor];
txt.text = @"1";
[self.view addSubview:txt];
//设置view的标签值
//通过父亲视图对象以及view的标签值可以获得相应的视图对象
txt.tag=101;
}
3.启动定时器和停止定时器
// 启动定时器
-(void)startTimer{
//NSTime的类方法创建一个定时器并且启动这个定时器
//p1:每个多长时间调用定时器函数,以秒为单位
//p2:表示实现这个定时器函数的对象
//p3:定时器函数对象
//p4:可以传入定时器函数中一个参数,无参数传入nil
//p5:定时器是否重复操作YES表示重复,NO表示只完成一次函数调用
_nsTime = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime:) userInfo:@"哈哈" repeats:YES];
}
-(void)updateTime:(NSTimer*) timer{
NSLog(@"参数为:%@",timer.userInfo);
UITextView* txt = [self.view viewWithTag:101];
int count = [txt.text intValue];
txt.text = [NSString stringWithFormat:@"%d",count+1];
}
// 停止定时器
-(void)stopTimer{
[_nsTime invalidate];
}