2017-06-02 39 views

回答

0

创建progressView具有所需backgroundColor

let progressView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 50)) 
progressView.backgroundColor = .blue 
self.view.addSubview(progressView) 

调用下面的函数进行动画其宽度正比于progress

func setProgress(_ progress: CGFloat) { 
    let fullWidth: CGFloat = 200 
    let newWidth = progress/100*fullWidth 
    UIView.animate(withDuration: 1.5) { 
     self.progressView.frame.size = CGSize(width: newWidth, height: self.progressView.frame.height) 
    } 
} 

创建progressLabelcurrentProgress可变

let progressLabel = UILabel(frame: CGRect(x: 0, y: 100, width: 50, height: 50)) 
var currentProgress: CGFloat = 0 
label.text = String(currentProgress) 
self.view.addSubview(progressLabel) 

调用下面的函数与延迟一个循环更新的进度,例如:setLabelProgress(initialValue: self.currentProgress, targetValue: 70)

func setLabelProgress(initialValue: CGFloat, targetValue: CGFloat) { 

    guard currentProgress != targetValue else { return } 

    let range = targetValue - initialValue 
    let increment = range/CGFloat(abs(range)) 
    let duration: TimeInterval = 1.5 
    let delay = duration/TimeInterval(range) 
    currentProgress += increment 
    progressLabel.text = String(describing: currentProgress) 

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay) { 
     self.setLabelProgress(initialValue: initialValue, targetValue: targetValue) 
    } 
} 

对于第二个标签调用相同的功能,但交换initialValuetargetValue

相关问题