我需要创建一个包含1或2个部分的表视图,具体取决于某些条件。第一部分需要包含当年的所有剩余月份,第二部分包含下一年的前几个月,直至但不包括当月。
示例:
2009
November
December
2010
January
February
March
April
May
June
July
August
September
October
这将是当前11月份的情景。但是,如果是1月份,则只有1个部分包含当年的所有12个月。
这一切都需要取决于手机的日期设置。
答案 0 :(得分:0)
我实际上已经开始工作......无论它是否是最好的方法都可供讨论。这是我提出的代码:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *monthArray = [NSArray arrayWithObjects:@"January", @"February", @"March", @"April", @"May", @"June", @"July", @"August", @"September", @"October", @"November", @"December", nil];
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
currentYear = [NSString stringWithFormat:@"%d", year];
nextYear = [NSString stringWithFormat:@"%d", year+1];
[dateComponents setMonth:month];
currentYearMonths = [[NSMutableArray alloc] init];
nextYearsMonths = [[NSMutableArray alloc] init];
for(uint i=month-1; i<=11; i++){
[currentYearMonths addObject:[monthArray objectAtIndex:i]];
}
for(uint i=0; i<month-1; i++){
[nextYearsMonths addObject:[monthArray objectAtIndex:i]];
}
monthList = [[NSArray alloc] initWithArray:monthArray];
[calendar release];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if([nextYearsMonths count] == 0)
return 1;
else
return 2;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(section == 0){
return currentYear;
}else if(section == 1){
return nextYear;
}
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0)
return [currentYearMonths count];
if(section == 1)
return [nextYearsMonths count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int section = [indexPath indexAtPosition:0];
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
int monthIndex = [indexPath indexAtPosition: [indexPath length] - 1];
switch (section) {
case 0:
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [currentYearMonths objectAtIndex:monthIndex];
break;
case 1:
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [nextYearsMonths objectAtIndex:monthIndex];
break;
}
return cell;
}