티스토리 뷰
저번 글에서 공부했던 DatePicker를 이용해 Timer를 만들어 보자.
StoryBoard와 ViewController는 다음과 같다.
DatePicker의 모드는 .countDownTimer로 설정한다.
datePicker.datePickerMode = .countDownTimer
datePicker Action을 추가하자.
Event가 Value Changed라고 되어있으므로 datePicker의 값이 변경될 때마다 Action이 호출된다.
datePicker의 값이 변경될 때마다 선택한 countDownDuration(= 카운트 다운 지속시간)이 얼마인지 출력해보았다.
Timer() 클래스를 이용해 countDownDuration만큼 Timer가 실행되도록 만들어보자.
ViewController.swift 전체 코드
//
// ViewController.swift
// DatePicker_Tutorial
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var timerLabel: UILabel!
var timer = Timer()
var timerSeconds = 0.0
override func viewDidLoad() {
super.viewDidLoad()
datePicker.datePickerMode = .countDownTimer
}
@IBAction func pickerValueChanged(_ sender: UIDatePicker) {
let picker = sender
timerSeconds = picker.countDownDuration
timerLabel.text = String(timerSeconds)
}
@IBAction func tappedStartButton(_ sender: UIButton) {
print("Tapped Start Button - Start Timer !")
timer.invalidate()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
}
@IBAction func tappedCancelButton(_ sender: UIButton) {
print("Tapped Cancel Button - Cancel Timer !")
timer.invalidate()
}
@objc func fireTimer() {
timerSeconds -= 1
timerLabel.text = String(Int(timerSeconds))
if( timerSeconds == 0 ) {
timer.invalidate()
}
}
}
'iOS' 카테고리의 다른 글
iOS) CocoaPods 사용하기 (0) | 2022.08.23 |
---|---|
iOS) UITabBarController Programmatically (0) | 2022.08.09 |
iOS) UIDatePicker - 1 (0) | 2022.07.24 |
iOS) UICollectionView Programmatically (0) | 2022.07.20 |
iOS) Error "UICollectionView must be initialized with a non-nil layout parameter" (0) | 2022.07.19 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- CAGradientLayer
- bottom sheet
- swift
- UICollectionView Error
- ios
- crud
- BOJ 10799
- Custom Detent
- Gradient View
- github
- git
- BOJ 10808
- BOJ 10809
- Algorithm
- Sheet Height
- BOJ 17298
- BOJ 1935
- Card CollectionVIew
- NaverMaps
- BOJ 10866
- 요시푸스
- UICollectionView banner
- BOJ 10820
- Carousel Effect
- sheetPresentationController
- BOJ 17413
- 1406 에디터
- 2023 회고
- Stack
- autolayout
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함