#import <UIKit/UIKit.h> @interface LYViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> { IBOutlet UILabel *timeLabel; NSTimer *timer; IBOutlet UITableView * tableView; IBOutlet UIButton *startAndEnd; int minute; int second; int millisecond; NSMutableArray * record; int isEnd; } -(IBAction)startAndEnd:(id)sender; -(void)updateTimer; -(IBAction)recordOnce:(id)sender; -(IBAction)reset:(id)sender; @end#import "LYViewController.h" @implementation LYViewController -(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { /// } return self; } - (void)viewDidLoad { //数组一定要先初始化 record=[[NSMutableArray alloc]init]; isEnd=0; [super viewDidLoad]; // /后台运行 // [self performSelectorInBackground:@selector(updateTimer) withObject:nil]; } -(IBAction)startAndEnd:(id)sender { if (isEnd==0) { [startAndEnd setTitle:@"暂停" forState:UIControlStateNormal]; timer=[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES] ; //增加进程 [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes]; isEnd=1; } else { [startAndEnd setTitle:@"开始计时" forState:UIControlStateNormal]; isEnd=0; [timer invalidate]; } } -(void)updateTimer { [timeLabel setText:[NSString stringWithFormat:@"%02d:%02d:%02d",minute,second,millisecond]]; millisecond++; if (millisecond==100) { millisecond=0; second++; if (second==60) { second=0; minute++; } } } -(IBAction)reset:(id)sender { [timer invalidate]; minute=0; second=0; millisecond=0; [timeLabel setText:[NSString stringWithFormat:@"%02d:%02d:%02d",minute,second,millisecond]]; record =nil; [tableView reloadData]; [startAndEnd setTitle:@"开始计时" forState:UIControlStateNormal]; isEnd=0; record=[[NSMutableArray alloc]init]; } -(IBAction)recordOnce:(id)sender; { NSString *temp=[NSString stringWithFormat:@"第%d次 %02d:%02d:%02d",[record count]+1,minute,second,millisecond]; [record addObject:temp]; [tableView reloadData]; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [record count]; } -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"]; [[cell textLabel] setText:[record objectAtIndex:[indexPath row]]]; return cell; } @end
简单定时器Demo
最新推荐文章于 2023-06-15 21:11:28 发布