계란이 익으면 텍스트 알람이 뜨는 부분까지 진행하였다. 이제 진행상황을 실시간으로 볼 수 있는 Progress Bar를 만들어보자.
2. Progress Bar 색상 변경
3. ProgressView와 IBOutlet 연결
ProgressView를 IBOutlet으로 ViewController로 연결해준다. 연결해야 소스코드와 ProgressView 진행상황을 연결할 수 있다.
4. percentageProgress = secondsPassed / totalTime
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var titleLabel: UILabel!
let eggTimes = ["Soft": 300, "Medium":420, "Hard": 720]
// 각 굽기정도 딕셔너리 형태로 seconds 초기화
var secondsRemaining = 60
var timer = Timer()
var totalTime = 0
var secondsPassed = 0
@IBAction func harnessSelected(_ sender: UIButton) {
timer.invalidate() // 타미어가 이미 실행되고 있었다면 중단시키는 함수 (Stops the timer from ever firing again and requests its removal from its run loop.)
let hardness = sender.currentTitle!
// Soft, Medium, Hard
// 모든 버튼들이 IBAction에 연결되어있다고 알려주는 Optional !
// It won't fail or crash !!
totalTime = eggTimes[hardness]!
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
// @objc 추가해주기
if secondsPassed < totalTime { // 지나간 시간이 전체 시간보다 작으면
secondsPassed += 1 // 시간이 1만큼 증가
let percentageProgress = Float(secondsPassed) / Float(totalTime)
// 나눈 이후에 Float로 형변환을 해주면 원하는 값이 나오지 않는다
// 나누기 전에 형변환을 해야 정확한 값을 얻을 수 있다
progressBar.progress = Float(percentageProgress)
}
else {
timer.invalidate() // 타이머를 멈춘다
titleLabel.text = "Done"
}
}
}
progressBar.progress = 0.0
secondsPassed = 0
titleLabel.text = hardness