Project 02 - Timer

DaY·2021년 3월 19일
1

iOS

목록 보기
10/52
post-thumbnail

Timer는 scheduledtimer() 클래스 메서드를 사용해 지정 초 간격으로 target-action을 수행한다.

let timer = Timer.scheduledTimer(timeInterval: TimeInterval, target: Any, selector: #Selector, userInfo: Any?, repeats: Bool)

timeInterval : 타이머 실행 간격(초) Double 타입
target : 함수 selector가 호출되어야 하는 클래스 인스턴스 (보통 self)
selector : 타이머가 실행될 때 호출 할 함수
userInfo : selectord에 제공되는 데이터가 있는 dictionary
repeats : 타이머 반복 여부 Bool 타입

타이머 중지

timer.invalidate()

타이머는 RunLoop와 함께 작동한다. RunLoop는 순환(looping)을 유지하고 작업을 실행한다.
RunLoop에서 타이머를 수동으로 예약하여 기본 스레드의 실행루프 사용 시 타이머가 실행되지 않는 문제를 해결할 수 있다.

RunLoop.current.add(timer, forMode: RunLoop.Mode.common)

common 입력 모드를 사용해 현재 RunLoop에 타이머를 추가한다.
이는 모든 공통 입력 모드에 대해 타이머를 확인해야 함을 알려주어 UI와 상호작용 하는 동안 타이머가 효과적으로 실행될 수 있다.

본 프로젝트에서는 timeInterval 간격을 0.035초로 지정했다.
0.035초 간격마다 다음과 같은 action이 반복된다.

func updateTimer(_ time: Time, label: UILabel) {
    time.counter = time.counter + 0.035
        
    var minutes: String = "\((Int)(time.counter / 60))"
        
    if (Int)(time.counter / 60) < 10 {
        minutes = "0\((Int)(time.counter / 60))"
    }
        
    var seconds: String = String(format: "%.2f", (time.counter.truncatingRemainder(dividingBy: 60)))
        
    if time.counter.truncatingRemainder(dividingBy: 60) < 10 {
        seconds = "0" + seconds
    }
    label.text = minutes + ":" + seconds
}

minutes : 카운트 된 시간을 60으로 나눈 몫
seconds : 카운트 된 시간을 60으로 나눈 나머지

minutes, seconds 값이 0.035초 마다 update 된다.

swift에서 % (나머지) 연산은 truncatingRemainder를 사용해야 한다.

0개의 댓글