将String转换为Float以移动UISlider

时间:2016-12-26 11:31:33

标签: ios objective-c uislider

如何将我的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

2 个答案:

答案 0 :(得分:0)

只需将duration从String转换为整数组件即可。 然后以秒为单位计算总持续时间。

您可以像这样获取整数组件:

夫特

let timeComponents = duration.components(separatedBy: ":")

目标C

NSArray *timeComponents = [duration componentsSeparatedByString:@":"];
  • timeComponents [0]将是小时部分。
  • timeComponents [1]将是分钟部分。
  • timeComponents [2]将是秒部分。

总秒数:(小时* 60 * 60)+(分钟* 60)+秒。

之后,调整滑杆值将很容易:)

答案 1 :(得分:0)

我认为没有内置机制将时间间隔转换为浮点数,但写起来很容易:

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
}