UICalendarView *calendarView = [[UICalendarView alloc] initWithFrame:(CGRectMake(15, 30, 300, 300))];
calendarView.delegate = self;
calendarView.tintColor = [UIColor systemBlueColor];
calendarView.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
calendarView.fontDesign = UIFontDescriptorSystemDesignRounded;
//初始化选中模式
UICalendarSelectionSingleDate *singleDateSelection = [[UICalendarSelectionSingleDate alloc]initWithDelegate:self];
NSString * timeStr = @"2023年10月24日";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//需要设置为和字符串相同的格式
[dateFormatter setDateFormat:@"yyyy年MM月dd日"];
NSDate *date = [dateFormatter dateFromString:timeStr];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:date];
//设置当前选中日期
[singleDateSelection setSelectedDate:components];
//设置选中模式为单选
calendarView.selectionBehavior = singleDateSelection;
[self.view addSubview:calendarView];
#pragma mark - UICalendarSelectionSingleDateDelegate
//选中了某个日期
- (void)dateSelection:(UICalendarSelectionSingleDate *)selection didSelectDate:(nullable NSDateComponents *)dateComponents API_AVAILABLE(ios(16.0)){
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *date = [calendar dateFromComponents:dateComponents];
//用于格式化NSDate对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//设置格式:zzz表示时区
[dateFormatter setDateFormat:@"yyyy年MM月dd"];
//NSDate转NSString
NSString *currentDateString = [dateFormatter stringFromDate:date];
_timeLabel.text = currentDateString;
}
//通过该方法可以设置可选日期范围
- (BOOL)dateSelection:(UICalendarSelectionSingleDate *)selection canSelectDate:(nullable NSDateComponents *)dateComponents API_AVAILABLE(ios(16.0)){
return [dateComponents.date compare:[NSDate date]] == NSOrderedAscending;
}