我希望在调整自定义滑块时在UILabel
显示HH:MM。目前我的自定义滑块返回浮动值,例如2.89,24.87 ......我希望将浮点值设为24.87并将其更改为24:52我在下面的代码中得到了所有工作但我认为它不是最有效的方式。任何人都可以改善吗?谢谢
- (void)slideValueChanged:(id)control
{
NSLog(@"Slider value changed: (%.2f,%.2f)",
_rangeSlider.lowerValue, _rangeSlider.upperValue);
lblStart.text = [NSString stringWithFormat:@"Start Time : %@", [self floatToTime:_rangeSlider.lowerValue]];
lblEnd.text = [NSString stringWithFormat:@"End Time : %@",[self floatToTime:_rangeSlider.upperValue]];
}
- (NSString*)floatToTime:(float)floatTime {
NSInteger iHour = floatTime;
CGFloat floatMin = floatTime - iHour;
NSString *sHour = [NSString stringWithFormat:@"%li", (long)iHour];
if (floatMin == 0.99) { //=== When the float is 0.99, convert it to 0, if not 60*0.99 = 59.4, will never get to 0
floatMin = 0;
}else{
floatMin = floatMin * 60;
}
NSInteger iMin = floatMin; //=== Take the integer part of floatMin
NSString *sMin = [[NSString alloc] init];
if (iMin <10){ //=== Take care if 0,1,2,3,4,5,6,7,8,9 to be 00,01,02,03...
sMin = [NSString stringWithFormat: @"0%li", iMin];
}else{
sMin = [NSString stringWithFormat: @"%li", iMin];
}
NSString *strFloatTime = [NSString stringWithFormat:@"%@:%@", sHour,sMin];
return strFloatTime;
}
答案 0 :(得分:1)
您可以使用格式显示两位数字,这简化了创建时间字符串的步骤:
CGFloat time = 24.87;
int hours = fabs(time);
int minutes = (int)((time - hours) * 60.0);
NSLog(@"Time: %02d:%02d", hours, minutes);
结果:&#34;时间:24:52&#34;
&#39; 02&#39;是位数。