UIProgressView 進度指示器


宣告資料

var line = UIProgressView()
var button = UIButton()
var countdown = Timer()
var count: Float = 0
let WIDTH = UIScreen.main.bounds.size.width

viewDidLoad

  • 背景顏色
    view.backgroundColor = .black
    
  • UIProgressView
        // 指示器樣式
        line = UIProgressView(progressViewStyle: .default)
        /*
         UIProgressView
         .default
         .bar
         */
        // 大小
        line.frame.size = CGSize(width: WIDTH,
                                 height: 50)
        // 中心點
        line.center = CGPoint(x: WIDTH / 2,
                              y: 75)
        // 初始值
        line.progress = 0
        // 進度條左邊顏色
        line.progressTintColor = .blue
        // 進度條右邊顏色
        line.trackTintColor = .white
    view.addSubview(line)
    
  • UIButton(觸發UIProgressView)
        button.frame.size = CGSize(width: 100,
                                   height: 50)
        button.center = CGPoint(x: WIDTH / 2,
                                y: 125)
        button.setTitle("執行",
                        for: .normal)
        button.backgroundColor = .blue
        button.layer.cornerRadius = 20
        button.addTarget(self,
                         action: #selector(buttonpressed),
                         for: .touchDown)
    view.addSubview(button)
    

讀取動作

func buttonpressed(sender: UIButton) {

    // 進度歸零
    line.progress = 0
    // 建立計時器
    countdown = Timer.scheduledTimer(timeInterval: 0.1,
                                     target: self,
                                     selector: #selector(timeron),
                                     userInfo: [],
                                     repeats: true)
    button.setTitle("讀取中",
                    for: .normal)
    button.backgroundColor = .red
}

計時器動作

func timeron(sender: Timer) {
    // 每回增加1點
    count += 1
    // 全滿40 點
    let complete: Float = 40
    let progress: Float = count / complete
    let color: Float = (complete - count) / complete

    line.progress = progress
    line.trackTintColor = UIColor(red: CGFloat(color),
                                  green: CGFloat(color),
                                  blue: CGFloat(color),
                                  alpha: 1)
    view.backgroundColor = UIColor(red: CGFloat(progress),
                                   green: CGFloat(progress),
                                   blue: CGFloat(progress),
                                   alpha: 1)
    if count == complete {
        // 計數歸零
        count = 0
        // 進度歸零
        line.progress = 0
        // 計時器停止動作
        countdown.invalidate()
        button.setTitle("執行",
                        for: .normal)
        button.backgroundColor = .blue
    }
}

下載完整範例 OneDrive

results matching ""

    No results matching ""