Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
31 |
Tags
- uikit
- Git
- SWIFTUI
- IOS
- struct
- apns
- Animation
- NotificationCenter
- list
- class
- SWIFT
- array
- Switch
- error
- 화면전환
- self
- escaping
- Refresh
- 고차함수
- calendar
- ScrollView
- mvvm
- 글또
- http
- protocol
- PushNotification
- Observer
- singleton
- segue
- viewlifecycle
Archives
- Today
- Total
seong_hye, the developer
iOS) Calendar에 대해 알아보기 본문
📘 Calendar
날짜별 장식이 있는 일정관리를 표시하고, 단일 날짜 또는 여러 날짜를 사용자가 선택할 수 있도록 제공하는 기능
캘린더 뷰를 사용하여 사용자가 커스터마이징한 추가 정보(ex_ 스케줄)가 있는 특정 날짜 표시
또한 캘린더 뷰를 사용하여 하나의 특정 날짜, 여러 날짜 또는 날짜가 없는 날짜를 선택 가능
🔹Calendar란
Foundation 프레임워크의 구조체
달력 시스템에 따라 날짜를 계산하고 연도/월/일/요일 등 구성 요소 추출 및 연산을 도와줌
✅ 날짜 더하기 / 빼기
let today = Date()
let calendar = Calendar.current
// 5일 후
let fiveDaysLater = calendar.date(byAdding: .day, value: 5, to: today)!
// 1개월 전
let oneMonthAgo = calendar.date(byAdding: .month, value: -1. to: today)!
✅ 특정 날짜 만들기
let calendar = Calendar.current
let date = calendar.date(from: DateComponents(year:2023, month: 12, day: 25))!
✅ 날짜 간 차이 계산
let start = Date()
let end = Calendar.current.date(byAdding: .day, value: 10, to: strart)!
let diff = Calendar.current.dateComponenets([.day], from: start, to: end)
print("날짜 차이 \(diff.day!)일") // 10일
✅ 날짜 시스템 설정
let iso = Calendar(identifier: .iso8601)
let buddhist = Calendar(identifier: .buddhist)
let korean = Calendar(identifier: .republicOfKorea)
✅ DateFormatter와 함께 사용
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.dateFormat = "yyyy-MM-dd"
let date = Date()
prihnt(formatter.string(from: date))
🔹UICalendarView 추가 방법
1.캘린더 뷰가 표시되도록 Calendar & Locale 설정
// Create the calendar view.
let calendarView = UICalendarView()
// Create an instance of the Gregorian calendar.
let gregorianCalendar = Calendar(identifier: .gregorian)
// Set the calendar displayed by the view.
calendarView.calendar = gregorianCalendar
// Set the calendar view's locale.
calendarView.locale = Locale(identifier: "zh_TW")
// Set the font design to the rounded system font.
calendarView.fontDesign = .rounded
2. 캘린더 뷰에 처음에 표시할 날짜 설정
- 한 날짜 선택 시
// Set the date to display.
calendarView.visibleDateComponents = DateComponents(
calendar: gregorianCalendar,
year: 2024,
month: 2,
day: 1
)
- 여러 날 선택 시
// Specify the starting date.
let fromDateComponents = DateComponents(
calendar: gregorianCalendar,
year: 2024,
month: 1,
day: 1
)
// Specify the ending date.
let toDateComponents = DateComponents(
calendar: gregorianCalendar,
year: 2024,
month: 12,
day: 31
)
// Verify that you have valid start and end dates.
guard let fromDate = fromDateComponents.date, let toDate = toDateComponents.date else {
// Handle the error here.
fatalError("Invalid date components: \(fromDateComponents) and \(toDateComponents)")
}
// Set the range of dates that people can view.
let calendarViewDateRange = DateInterval(start: fromDate, end: toDate)
calendarView.availableDateRange = calendarViewDateRange
3. 원하는 경우 특정 날짜에 장식을 제공할 delegate 작성
// Define a calendar view delegate.
class CalendarViewDelegate: NSObject, UICalendarViewDelegate {
var calendarView: UICalendarView? = nil
var decorations: [Date?: UICalendarView.Decoration]
override init() {
// Create the date components for Valentine's day that
// contain the calendar, year, month, and day.
let valentinesDay = DateComponents(
calendar: Calendar(identifier: .gregorian),
year: 2024,
month: 2,
day: 14
)
// Create a calendar decoration for Valentine's day.
let heart = UICalendarView.Decoration.image(
UIImage(systemName: "heart.fill"),
color: UIColor.red,
size: .large
)
decorations = [valentinesDay.date: heart]
}
// Return a decoration (if any) for the specified day.
func calendarView(_ calendarView: UICalendarView, decorationFor dateComponents: DateComponents) -> UICalendarView.Decoration? {
// Get a copy of the date components that only contain
// the calendar, year, month, and day.
let day = DateComponents(
calendar: dateComponents.calendar,
year: dateComponents.year,
month: dateComponents.month,
day: dateComponents.day
)
// Return any decoration saved for that date.
return decorations[day.date]
}
}
4. 날짜 선택을 처리할 선택 메서드 및 delegate 설정
// Add a decoration to the specified date.
func add(decoration: UICalendarView.Decoration, on date: Date) {
// Get the calendar, year, month, and day date components for
// the specified date.
let dateComponents = Calendar.current.dateComponents(
[.calendar, .year, .month, .day ],
from: date
)
// Add the decoration to the decorations dictionary.
decorations[dateComponents.date] = decoration
// Reload the calendar view's decorations.
if let calendarView {
calendarView.reloadDecorations(
forDateComponents: [dateComponents],
animated: true
)
}
}
// Control whether a person can select a given date.
func dateSelection(
_ selection: UICalendarSelectionSingleDate,
canSelectDate dateComponents: DateComponents?
) -> Bool {
// Allow all dates by returning true if the selection parameter contains
// a date component instance. Prevent someone from clearing the selection
// by returning false if the selection parameter is nil.
return dateComponents != nil
}
// Respond when someone selects or deselects a date. If they selected
// a date, the dateComponent parameter contains the selected date. If they
// cleared the selection, the parameter is nil.
func dateSelection(_ selection: UICalendarSelectionSingleDate, didSelectDate dateComponents: DateComponents?) {
// Update your app.
}
5. Auto Layout을 설정하여 인터페이스에 캘린더 배치
calendarView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
calendarView.topAnchor.constraint(equalTo: safeArea.topAnchor)
calendarView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor)
calendarView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor)
calendarView.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor)
])
🔹SwiftUI에서 활용법
DatePicker, CalendarView 등의 컴포넌트와 함께 사용
DatePicker("날짜 선택", selection: $date, displayedComponents: [.date])
'IOS > UIKit' 카테고리의 다른 글
Swift) 책과 같이 페이지 넘기는 애니메이션에 대해 알아보기 (UIPageViewController) (0) | 2025.06.25 |
---|---|
UIKit) Calendar / Weekly Calendar 구현해보기 (2) | 2024.02.04 |
Swift) UISearchController에 대해 알아보기 (0) | 2022.11.08 |
Swift) UIActivityViewController에 대해 알아보기 (ShareSheet) (0) | 2022.11.06 |
UIKit) UICollectionvView - layout vs flowlayout (0) | 2022.11.06 |
Comments