2017-06-02 38 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

相關問題