定时器的开始与暂停
查看次数:2949
下载次数:219
上传时间:2014-11-11
大小:69 B
//
// ViewController.m
// timer
//
// Created by apple on 14/11/11.
// Copyright (c) 2014年 guocheng. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
{
int i ;
NSTimer *timer;
UILabel * label;
}
@end
@implementation ViewController
- (void )viewDidLoad {
[ super viewDidLoad];
//创建定时器
timer = [NSTimer scheduledTimerWithTimeInterval :1 target:self selector:@selector (labeltext) userInfo:nil repeats:YES ];
// 让定时器处于关闭状态
[ timer setFireDate:[ NSDate distantFuture]];
UIButton * button = [ UIButton buttonWithType: UIButtonTypeCustom];
button.frame = CGRectMake (50 , 50 , 50 , 50 );
[button setTitle: @" 开始 " forState: UIControlStateNormal];
[button setTitle: @" 暂停 " forState: UIControlStateSelected];
[button addTarget :self action:@selector (buttonClick:) forControlEvents:UIControlEventTouchUpInside ];
button. backgroundColor = [ UIColor redColor];
[self .view addSubview :button];
[self createUI ];
}
-(void )buttonClick:(UIButton *)bt{
if (bt.selected ==YES ) {
NSLog (@"ddddddddd" );
//当 button 处于选择状态的时候 开启定时器
[ timer setFireDate:[ NSDate distantFuture]];
//将 button的状态至为 no
bt.selected =NO ;
}
else {
NSLog (@"PPPPPPP" );
bt.selected =YES ;
[ timer setFireDate:[ NSDate distantPast]];
}
}
-(void )labeltext{
NSLog ( @"111111");
i ++;
label . text =[ NSString stringWithFormat: @"%d" , i ];
}
-(void )createUI{
label = [[ UILabel alloc] initWithFrame: CGRectMake( 100 , 100 , 100 , 100 )];
[self .view addSubview :label ];
}
// 页面消失,进入后台不显示该页面,关闭定时器
-(void )viewDidDisappear:(BOOL )animated
{
//关闭定时器
[ timer setFireDate:[ NSDate distantFuture]];
}
- (void )didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
收藏