2009-11-18 2 views
0

Мне нужно создать представление таблицы с 1 или 2 разделами, в зависимости от определенных условий. Первый раздел должен содержать все оставшиеся месяцы текущего года, а второй раздел содержит предыдущие месяцы следующего года, вплоть до текущего месяца.Month TableView Organizer

Пример:

2009 
    November 
    December 

2010 
    January 
    February 
    March 
    April 
    May 
    June 
    July 
    August 
    September 
    October 

Это будет сценарий с текущим месяцем ноября. Однако, если бы это был январь, было бы только 1 раздел, содержащий все 12 месяцев текущего года.

Все это должно зависеть от настроек даты телефона.

+3

и вопрос? – ennuikiller

+0

Как это сделать? – rson

+2

Что вы думаете? Как разработчик, вам придется анализировать проблемы и решать их, а не спрашивать, как сделать что-то сразу. Вы разработчик, мы хотя бы ожидаем, что вы что-нибудь попробуете. Расскажите, что вы уже пробовали, и с какими проблемами вы столкнулись. – Joost

ответ

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; 
} 
+1

Итак, у вас есть это работает всего через 2 часа. Хорошая работа, вы действительно можете сделать это самостоятельно, хотя это может занять некоторое время (и 2 часа не так уж и много). Одна вещь: инициализировать ячейку сразу после того, как вы удалите ее, что сэкономит вам много копий в коммутаторе. – Joost

Смежные вопросы