我正在创建一个倒计时,并希望在倒计时标签下的适当位置显示倒计时时间以及单位名称(年,月,日,小时,分钟,秒)。我有一个名为 countdownLabel 的UILabel对象,我使用故事板将其放入UIView子视图中。 countdownLabel的大小跨越了它所在的子视图的宽度,并为我想要添加的时间单位标签留下了一点空间。
我有一个NSTimer调用updateLabel方法来更新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;
}
应用程序的计时器方面工作得很好。但是,我似乎无法弄清楚如何在运行时添加时间单位标签,以便我只根据倒计时标签中显示的内容添加我需要的标签,并让时间单位标签在相应的时间内对齐在倒计时标签下面。
我尝试过使用method that extracted the respective time value as a substring,然后根据子字符串rect计算出时间单位标签的位置,但它不能很好地工作或看起来很漂亮。
必须有一种更简单的方法来做到这一点,我只是学习目标C所以任何帮助都会非常感激!