I have the following code for a stopwatch function.
I have 2 UIButtons. One is for start/stop, the other is for reset.
I want to combine these 2 into just 1 button, that functions as a start button, then while the timer is running, it will be a stop button, that when pushed, resets the timer.
How can I modify this code to reflect this?
- (IBAction)startStop:(UIButton *)sender
{
if ( self.myTimer )
{
[self.myTimer invalidate];
self.myTimer = nil;
[sender setTitle:@"Start" forState:UIControlStateNormal];
}
else
{
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
[sender setTitle:@"Stop" forState:UIControlStateNormal];
}
}
- (void)handleTimer:(NSTimer *)timer
{
self.counter--;
self.timerLabel.text = [NSString stringWithFormat:@"%ld", self.counter];
if ( self.counter <= 0 )
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
[self.myTimer invalidate];
self.myTimer = nil;
self.timerButton.enabled = NO;
}
}
- (IBAction)reset:(id)sender
{
self.timerButton.enabled = YES;
self.counter = self.counterSegment;
self.timerLabel.text = timerCount;
self.timerButton.titleLabel.text = @"Start";
self.timerButton.titleLabel.adjustsFontSizeToFitWidth = YES;
}
- (void)segmentedControl:(SVSegmentedControl*)segmentedControl didSelectIndex:(NSUInteger)index
{
if ( self.myTimer )
{
[self.myTimer invalidate];
self.myTimer = nil;
self.timerButton.titleLabel.text = @"Start";
self.timerButton.titleLabel.adjustsFontSizeToFitWidth = YES;
}
else
{
self.timerButton.enabled = YES;
self.counter = self.counterSegment;
self.timerLabel.text = timerCount;
self.timerButton.titleLabel.text = @"Start";
self.timerButton.titleLabel.adjustsFontSizeToFitWidth = YES;
}
if (index == 0)
{
NSLog(@"15 sec");
self.timerCount = @"15";
self.counterSegment = 15;
}
else if (index == 1)
{
NSLog(@"30 sec");
self.timerCount = @"30";
self.counterSegment = 30;
}
}
Steps you could do:
remove the reset button from you UI;
modify the
startStopmethod so that when pressed while the timer is already running, it will send aresetmessage to itself:I think it should be enough. Have a look at this code:
Since in
resetyou are not using thesenderargument, you can remove it and have:In this way you will be able to use this method in a more generic way.