I'm creating a countdown and want to display the countdown time as well as the unit names (years, months, days, hours, minutes, seconds) under the countdown label at the appropriate position. I have a UILabel object called countdownLabel which I put into a UIView subview using the story board. The size of the countdownLabel spans the width of the subView it's in and leaves a little room for the time unit labels that I want to add.
I have a NSTimer that calls the updateLabel method to update the countdownLabel
- (void)updateLabel
{
NSString *counterStr;
self.dateComponents = [self.gregorianCalendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit)
fromDate:[NSDate date]
toDate:self.countdownDate
options:0];
int yearsRemaining = [self.dateComponents year];
int monthsRemaining = [self.dateComponents month];
int daysRemaining = [self.dateComponents day];
int hoursRemaining = [self.dateComponents hour];
int minutesReamining = [self.dateComponents minute];
int secondsReamining = [self.dateComponents second];
if ((yearsRemaining + monthsRemaining + hoursRemaining + minutesReamining + secondsReamining) > 0)
{
if (yearsRemaining == 0 && monthsRemaining == 0 && daysRemaining == 0 && hoursRemaining == 0)
counterStr = [NSString stringWithFormat:@"%02d:%02d", minutesReamining, secondsReamining];
else if (yearsRemaining == 0 && monthsRemaining == 0 && daysRemaining == 0)
counterStr = [NSString stringWithFormat:@"%02d:%02d:%02d", hoursRemaining, minutesReamining, secondsReamining];
else if (yearsRemaining == 0 && monthsRemaining == 0)
counterStr = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d", daysRemaining, hoursRemaining, minutesReamining, secondsReamining];
else if (yearsRemaining == 0)
counterStr = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d:%02d", monthsRemaining, daysRemaining, hoursRemaining, minutesReamining, secondsReamining];
else
counterStr = [NSString stringWithFormat:@"%i:%02d:%02d:%02d:%02d:%02d", yearsRemaining, monthsRemaining, daysRemaining, hoursRemaining, minutesReamining, secondsReamining];
}
else
counterStr = @"Countdown Ended!";
self.countdownLabel.text = counterStr;
}
The timer aspect of the app works just fine. However, I can't seem to figure out how to add the time unit labels at run time so that I only add the labels I need based on whats shown in the countdown label and have the time unit labels align under the respective time below the countdown label.
I've tried using a method that extracted the respective time value as a substring and then figured out where to put the the time unit label based on that substring rect, but it didn't work well or look pretty.
There has to be an easier way to do this and I'm just learning Objective C so any help would be much appreciated!