上午12点/上午时间

时间:2016-09-27 23:20:27

标签: swift time slider

我想显示从Slider到Label的时间。所以我必须转换价值并获得当天的时间,如上午00:00 /下午。 所以我需要一个步进器如何打印所有5个步骤,如(5,10,15,20,25 .... 50,55) 所以这个底部的代码运行不好,有没有人有更好的方法来做到这一点?

我已经尝试了但是当我向后滑动时它会变成一个错误(zb:当它是早上8点,我滑回到早上7点55分它是第一个上午7点来。

以下是代码:

   func valueChange(_ sender: CircleSlider) {

    let countmin = Int(Double(sender.value) * 14.4)
    var hour = countmin / 60
    let mins = countmin - (hour*60)


    if hour >= 12 {
        hour -= 12
        Am.text = "Pm"
    } else {
        Am.text = "Am"
    }



    hours = hour


    let i = String(mins) 
    switch i {
        case "Nil":
            minutes = 00
        case "0":
            minutes = 00
        case "5":
            minutes = 05
        case "10":
            minutes = 10
        case "15":
            minutes = 15
        case "25":
            minutes = 25
        case "30":
            minutes = 30
        case "35":
            minutes = 35
        case "40":
            minutes = 40
        case "45":
            minutes = 45
        case "50":
            minutes = 50
        case "55":
            minutes = 55
        case "60":
            minutes = 60
        default:
            break
    }


    self.circleTime.text = "\(String(format: "%02d", hours!)):\(String(format: "%02d", minutes!))"
}

感谢您的帮助:)

1 个答案:

答案 0 :(得分:2)

我认为7:56,7:57,7:58,7:59的方法存在问题(并没有很好地截断)。此代码应该适合您:

func valueChange(_ sender: CircleSlider) {
    let countmin = Int(Double(sender.value) * 14.4)

    var hour = countmin / 60
    let mins = countmin - (hour * 60)

    if hour >= 12 {
        hour -= 12
        Am = "Pm"
    } else {
        Am = "Am"
    }

    hours = hour
    minutes = roundToFives(Double(mins))

    // This fixes when you have hh:60. For instance, it fixes 7:60 to 8:00
    if minutes == 60 {
        hours = hour + 1
        minutes = 0
    }

    self.circleTime.text = "\(String(format: "%02d", hours!)):\(String(format: "%02d", minutes!))"
}

// idea of this method comes from: http://stackoverflow.com/questions/27922406/round-double-to-closest-10-swift
private func roundToFives(x : Double) -> Int {
    return 5 * Int(round(x / 5.0))
}