将 String 转换为 Float 以移动 UISlider
Posted
技术标签:
【中文标题】将 String 转换为 Float 以移动 UISlider【英文标题】:Convert String to Float to move UISlider 【发布时间】:2016-12-26 11:31:32 【问题描述】:如何将 JSON 数据的时间转换为浮点值。下面的代码用于将时间转换为浮点数,我将它作为音频的总长度传递给 UISlider。我想用那个时间跨度移动滑块
//Json Data
duration = "00:03:45";
id = 8;
//音频播放器侧边栏功能
if(audioController.playbackState == MPMusicPlaybackStatePlaying)
if (isSelected == YES)
currentAutio = audioList[selectedAudio];
else
currentAutio = audioList[0];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
float value = [numberFormatter numberFromString:currentAutio.duration].floatValue;
float currentPlaybackTime = [audioController currentPlaybackTime];
float TotalLength = value;
float remainingPlaybackTime = TotalLength - currentPlaybackTime;
float sliderPosition = (currentPlaybackTime *100) / TotalLength;
NSLog(@"current playbacktime %f",currentPlaybackTime);
NSLog(@"TotalLength %f",TotalLength);
NSLog(@"remainingPlaybackTime %f",remainingPlaybackTime);
NSLog(@"sliderPosition %f",sliderPosition);
//Update slider
[progressSlider setValue:sliderPosition];
//Update labels
NSDate* d1 = [NSDate dateWithTimeIntervalSince1970:currentPlaybackTime];
NSDate* d2 = [NSDate dateWithTimeIntervalSince1970:remainingPlaybackTime];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:d1];
NSString *ramainingTime = [dateFormatter stringFromDate:d2];
[trackCurrentPlaybackTimeLabel setText:currentTime];
[trackLengthLabel setText:[NSString stringWithFormat:@"-%@",ramainingTime]];
我得到以下输出: 值 = 0.00000
【问题讨论】:
你期望从给定的3:45
得到什么 float 值?
【参考方案1】:
我不认为有将时间间隔转换为浮点数的内置机制,但它很容易编写:
func timeIntervalFrom(_ timeString: String) -> TimeInterval?
//Add code to validate that string is in correct format
let components = time.components(separatedBy: ":")
guard components.count == 3,
let hours = Double(components[0]),
let minutes = Double(components[1]),
let seconds = Double(components[2]) else
return nil
return hours * 3600 + minutes * 60 + seconds
【讨论】:
【参考方案2】:只需将duration
从字符串转换为整数组件。
然后以秒为单位计算总时长。
你可以像这样简单地得到整数分量:
斯威夫特
let timeComponents = duration.components(separatedBy: ":")
目标 C
NSArray *timeComponents = [duration componentsSeparatedByString:@":"];
timeComponents[0] 将是小时部分。
timeComponents[1] 将是分钟部分。
timeComponents[2] 将是秒部分。
总秒数:(小时 * 60 * 60)+(分钟 * 60)+ 秒。
之后,调整滑动条的值会很容易:)
【讨论】:
以上是关于将 String 转换为 Float 以移动 UISlider的主要内容,如果未能解决你的问题,请参考以下文章