我试图通过传递进度指示器(Double)在指定的时间段内连续调用函数,在这段时间内应该从0变为1.有没有办法在
Swift中将这种变化从0变为1?
更新:
这是我基于https://github.com/danielgindi/ios-charts更新饼图数据的代码
internal func animateDataChange(fromDataSet: PieChartDataSet, toDataSet: PieChartDataSet, progress: Double) -> PieChartDataSet {
var dataEntries: [ChartDataEntry] = []
for i in 0..<fromDataSet.yVals.count {
let yValue = (toDataSet.yVals[i].value - fromDataSet.yVals[i].value) * progress + fromDataSet.yVals[i].value
let dataEntry = ChartDataEntry(value: yValue, xIndex: i)
dataEntries.append(dataEntry)
}
let animatedDataSet = PieChartDataSet(yVals: dataEntries, label: "")
return animatedDataSet
}
我想要做的是为两个数据集之间的变化设置动画,并且变化的进度反映在“progress”参数中.我需要继续调用函数,直到“progress”= 1.
最佳答案 我决定使用NSTimer来将计数器从0.01增加到每0.01秒1.我知道这可能不是最有效的方式,但它有效:
var progress: Double = 0
var timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target:self, selector: Selector("updateProgress"), userInfo: nil, repeats: true)
func updateProgress() {
guard progress <= 1 else {
timer.invalidate()
return
}
progress += 0.01
}