2016年12月26日 星期一

[IOS] Progress View



  1. @IBOutlet weak var btnStart: UIButton!
  2. @IBOutlet weak var progress: UIProgressView!
  3. @IBOutlet weak var labelMsg: UILabel!
  4. //計時器
  5. var timer: Timer?
  6. //計數
  7. var count : Int = 0
  8. override func viewDidLoad() {
  9. super.viewDidLoad()
  10. progress.frame.size.width = 250
  11. //可以自訂progress顏色
  12. progress.progressTintColor = UIColor.red
  13. progress.trackTintColor = UIColor.darkGray
  14. progress.progress = 0
  15. }
  16.  
  17. @IBAction func donloadClick(_ sender: UIButton) {
  18. //按鈕失效 避免重複點擊
  19. btnStart.isEnabled = false
  20. count = 0
  21. //參數順序亂掉會報錯
  22. //The runTimedCode selector means that the timer will call a method named runTimedCode() every 0.5 seconds until the timer is terminated
  23. timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector:#selector(runTimedCode), userInfo: nil, repeats: true)
  24. }
  25. func runTimedCode() {
  26. progress.progress = Float(count) / 100
  27. labelMsg.text = "process: \(count)%"
  28. count += 1
  29. if count > 100 {
  30. timer!.invalidate() // stop
  31. timer = nil
  32. btnStart.isEnabled = true
  33. }
  34. }
  35.  
參考資料:hackingwithswift.com

沒有留言:

張貼留言