@interface stopwatchViewController : UIViewController {
IBOutlet UILabel *lbl;
NSTimer *timer;
}
@property(nonatomic,retain) UILabel *lbl;
-(void)onTimer:(NSTimer*)timer;
- (IBAction) start_down:(id) sender;
- (IBAction) stop_down:(id) sender;
- (IBAction) clear_down:(id) sender;
@end
3、Interface builderで機能を繋げます
4、.mファイルに以下を記入
#import "stopwatchViewController.h"
@implementation stopwatchViewController
@synthesize lbl;
NSDate *stdate;
BOOL timeflg=FALSE;
- (void)onTimer:(NSTimer*)timer {
if(timeflg){
NSDate *now = [NSDate date];
self.lbl.text = [NSString stringWithFormat:@"%.3f",
[now timeIntervalSinceDate:stdate]];
}
}
-(IBAction) start_down:(id) sender{
timeflg = TRUE;
stdate = [NSDate date];
[stdate retain];
}
-(IBAction) stop_down:(id) sender{
timeflg = FALSE;
}
-(IBAction) clear_down:(id) sender{
timeflg = FALSE;
self.lbl.text = @"0.000";
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
timer = [NSTimer scheduledTimerWithTimeInterval:(0.001)
target:self
selector:@selector(onTimer:)
userInfo:nil
repeats:YES];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
これで完成!
うまくできましたでしょうか??