De videotutorial laat zien hoe je meerdere eenvoudig meerdere timers in een view kan verwerken. De timers worden getarget op basis van hun tag (dus zonder IBOutlet).
Code snippets
Hieronder vindt je de toegevoegde regels bij elke class.
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
NSMutableDictionary *defaultCounterDictionary;
NSMutableDictionary *counterDictionary;
}
@property (nonatomic, copy) NSMutableDictionary *defaultCounterDictionary;
@property (nonatomic, copy) NSMutableDictionary *counterDictionary;
- (IBAction)launchTimer:(id)sender;
- (void)changeCountdownLabel:(NSTimer *)timer;
@end
@synthesize defaultCounterDictionary, counterDictionary;
- (void)viewDidLoad
{
[super viewDidLoad];
defaultCounterDictionary = [[NSMutableDictionary alloc] init];
[defaultCounterDictionary setValue:@"10" forKey:@"1"];
[defaultCounterDictionary setValue:@"15" forKey:@"2"];
counterDictionary = [[NSMutableDictionary alloc] init];
[counterDictionary setValue:@"10" forKey:@"1"];
[counterDictionary setValue:@"15" forKey:@"2"];
}
- (IBAction)launchTimer:(id)sender
{
// Get button tag
UIButton *button = (UIButton*) sender;
NSString *buttonTag = [NSString stringWithFormat:@"%d", button.tag];
// Cancel timer if button hit for second time
UILabel *countdownLabel = (UILabel *)[self.view viewWithTag:button.tag + 20];
int countdownSeconds = [countdownLabel.text intValue];
if (countdownSeconds > 0)
{
[counterDictionary setValue:[NSString stringWithFormat:@"%d", 1] forKey:buttonTag];
}
else
{
// Launch timer
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeCountdownLabel:) userInfo:buttonTag repeats:YES];
}
}
- (void)changeCountdownLabel:(NSTimer *)timer
{
// Change countdown seconds
int countDownSeconds = [[counterDictionary objectForKey:[timer userInfo]] intValue];
countDownSeconds--;
[counterDictionary setValue:[NSString stringWithFormat:@"%d", countDownSeconds] forKey:[timer userInfo]];
// Timer ended
if (countDownSeconds <= 0)
{
UILabel *countdownLabel = (UILabel *)[self.view viewWithTag:[[timer userInfo] intValue] + 20];
countdownLabel.Text = @"timer 1";
// Set cooldown seconds to default value
NSString *defaultCounterDictionaryValue = [defaultCounterDictionary objectForKey:[timer userInfo]];
[counterDictionary setValue:defaultCounterDictionaryValue forKey:[timer userInfo]];
// Cancel timer
[timer invalidate];
timer = nil;
}
else
{
// Change label
UILabel *countdownLabel = (UILabel *)[self.view viewWithTag:[[timer userInfo] intValue] + 20];
countdownLabel.text = [NSString stringWithFormat:@"%d", countDownSeconds];
}
}



Recente reacties