How do I implement previous/next month buttons and show dates for current month?

前端 未结 2 1619
囚心锁ツ
囚心锁ツ 2021-01-16 20:24

Scenario:

I have an expense tracking iOS Application and I am storing expenses from a expense detail view controller into a table view (with fetched results controll

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-16 20:53

    Here are some methods that should do what you want:

    First, in your viewDidLoad method add:

    self.startDate = [NSDate date];
    [self updateDateRange];
    

    This gives you a starting point. Then, I added the following five methods (Note: previousMonthButtonPressed/nextMonthButtonPressed should be wired up to your buttons):

    // Return the first day of the month for the month that 'date' falls in:
    - (NSDate *)firstDayOfMonthForDate:(NSDate *)date
    {
        NSCalendar *cal         = [NSCalendar currentCalendar];
        NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                         fromDate:date];
        comps.day               = 1;
        return [cal dateFromComponents:comps];
    }
    
    // Return the last day of the month for the month that 'date' falls in:
    - (NSDate *)lastDayOfMonthForDate:(NSDate *)date
    {
        NSCalendar *cal         = [NSCalendar currentCalendar];
        NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                         fromDate:date];
        comps.month             += 1;
        comps.day               = 0;
        return [cal dateFromComponents:comps];
    }
    
    // Move the start date back one month
    - (IBAction)previousMonthButtonPressed:(id)sender {
        NSCalendar *cal         = [NSCalendar currentCalendar];
        NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                         fromDate:self.startDate];
        comps.month             -= 1;
        self.startDate          = [cal dateFromComponents:comps];
        [self updateDateRange];
    }
    
    // Move the start date forward one month
    - (IBAction)nextMonthButtonPressed:(id)sender {
        NSCalendar *cal         = [NSCalendar currentCalendar];
        NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                         fromDate:self.startDate];
        comps.month             += 1;
        self.startDate          = [cal dateFromComponents:comps];
        [self updateDateRange];
    }
    
    // Print the new range of dates.
    - (void)updateDateRange
    {
        NSLog(@"First day of month: %@", [self firstDayOfMonthForDate:self.startDate]);
        NSLog(@"Last day of month: %@",  [self lastDayOfMonthForDate:self.startDate]);
    }
    

提交回复
热议问题