STUDY/Swift & iOS

[Swift]Section 8 - Intermediate Swift Programming - Control Flow and Optionals

sinawi95 2023. 1. 31. 21:03
728x90

목표: Egg Timer 만들기

계란을 눌렀을때 타이머 돌아가게끔 만들면됨.

배운것

1. Optional

nil일수도 아닐수도 있습니다. 하지만 실제로 값을 사용하려면 unwrap을 해줘야함

https://developer.apple.com/documentation/swift/optional/

 

Apple Developer Documentation

 

developer.apple.com

 

2. Timer

지정된 interval 마다 selector에 연결된 콜백함수 실행

https://developer.apple.com/documentation/foundation/timer

 

Apple Developer Documentation

 

developer.apple.com

 

3. ProgressView

진행 상황을 볼 수 있는 UIView. 물론 업데이트를 계속 해줘야함.

https://developer.apple.com/documentation/swiftui/progressview/

 

Apple Developer Documentation

 

developer.apple.com

 

더보기

 

import UIKit

class ViewController: UIViewController {
    var counter: Int?
    var eggTimer: Timer?
    var selectedHardness: Int?
    
    @IBOutlet weak var timerProgress: UIProgressView!
    @IBOutlet weak var titleLabelText: UILabel!
    
    let eggTimes = [
        "Soft": 3,
        "Medium": 30,
        "Hard": 60
    ]
    
    func startTimer() {
        if eggTimer != nil {
            stopTimer()
            return
        }
        
        eggTimer = Timer.scheduledTimer(
            timeInterval: 1.0,
            target: self,
            selector: #selector(updateCounter),
            userInfo: nil,
            repeats: true
        )
    }
    func stopTimer() {
        eggTimer?.invalidate()
        eggTimer = nil
        selectedHardness = nil
    }
    
    @objc func updateCounter() {
        //example functionality
        
        if counter! > 0 {
            print("\(counter!) seconds.")
            let calcValue = 1.0 - (Float(counter!) / Float(selectedHardness!))
            timerProgress.progress = calcValue
            counter! -= 1
        }
        else{
            timerProgress.progress = 1.0
            titleLabelText.text! = "Done!"
            stopTimer()
        }
    }

    @IBAction func hardnessSelected(_ sender: UIButton) {
        let hardness = sender.currentTitle!
        titleLabelText.text = hardness
        counter = (eggTimes[hardness]!)
        selectedHardness = eggTimes[hardness]!
        startTimer()
    }
}