UICalendarView的使用

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值