2013-05-03 2 views
3

Мне нужно создать расширяемый список в моем приложении iOS, т.е. если вы нажмете на ячейку, она должна расширяться, чтобы дать больше ячеек. Я следую пример, приведенный на этой ссылке: Toggle showing/hiding child table cells iOS Код для файла реализации приведен здесь: http://pastie.org/7756763расширяемый просмотр списка в iOS

Однако, в приведенном выше примере массивы являются фиксированными. У меня есть база данных sqlite, где я храню задачи и их даты начала, среди прочего. Мне нужно создать расширяемое представление, где разные строки - разные даты начала и когда я нажимаю на дату, он должен давать задачи для этой даты. Вот код:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    allDates = [[NSMutableArray alloc]init]; 

    self.date = [[NSMutableArray alloc] initWithObjects: nil]; 
    // self.date = [[NSMutableArray alloc]init]; 
    self.listOfSections_DataSource = [[NSMutableArray alloc]initWithObjects:nil]; 

    sqlite3_stmt *statement; 
    const char *dbpath = [mDatabasePath UTF8String]; 
    if (sqlite3_open(dbpath,&mDiary)== SQLITE_OK) { 
     NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM TODO"]; 
     const char *query_stmt = [selectSQL UTF8String]; 
     if (sqlite3_prepare_v2(mDiary, 
           query_stmt, -1, &statement, NULL) == SQLITE_OK) 
     { 
        while(sqlite3_step(statement) == SQLITE_ROW) 
      { 
       tempTaskName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]; 
       [allDates addObject:[[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]]; 

       [self.date addObject:tempTaskName]; 


      } 

    } 
    sqlite3_finalize(statement); 
} 
sqlite3_close(mDiary); 

NSLog(@"%i",[allDates count]); 

     for(int x = 0;x < [allDates count];x++) 
     { 
      if (sqlite3_open(dbpath,&mDiary)== SQLITE_OK) { 
       NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM TODO"]; 
       const char *query_stmt = [selectSQL UTF8String]; 

       if (sqlite3_prepare_v2(mDiary, 
             query_stmt, -1, &statement, NULL) == SQLITE_OK){ 
      temp = [[NSMutableArray alloc]init]; 
      while(sqlite3_step(statement) == SQLITE_ROW) 
      { 
       tempTaskName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]; 
       NSLog(@"%@",tempTaskName); 
       // [allDates addObject:[[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]]; 
       if([[[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)] isEqualToString:allDates[x]]) 
       { 
        [self.temp addObject:tempTaskName]; 
       } 




      } 
      NSLog(@"task name%@",temp); 
      [listOfSections_DataSource addObject:temp]; 

       } sqlite3_finalize(statement); 
      } 
      sqlite3_close(mDiary); 
     } 

    //[self.listOfSections_DataSource addObject:allDates]; 

    NSMutableArray *emptyArray = [[NSMutableArray alloc]init]; 
    listOfSections = [[NSMutableArray alloc]init]; 
    for (int i = 0;i<[allDates count]; i++) { 
     [listOfSections addObject:emptyArray]; 
    } 
    self.selectedSection = -1; 
    self.selectedSectionTail = -1; 
} 

методы просмотра таблицы являются:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 


    return [listOfSections_DataSource count]; 


} 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    if(selectedSection !=section) 
     return 1; 
    else{ 
     NSArray *array = [listOfSections objectAtIndex:section]; 

     return [array count]; 
    } 

} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"cell"; 

    if(self.selectedSection == indexPath.section){//this is just to check to see if this section is the one we touched 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) 
     { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     } 

     NSArray *myArray = [listOfSections_DataSource objectAtIndex:indexPath.section];//this now contains your cities 
     NSString* myString = [myArray objectAtIndex:indexPath.row]; // get city for that row, under the state 

     cell.textLabel.text = myString; 
     return cell; 
    } 
    else{//THIS IS going to happen the first time 
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) 
     { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     } 

      cell.textLabel.text = @"more"; 

     return cell; 
    } 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 


    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath]; 

    //check to see if the cell is for exapnding or for selection 
    if([cell.textLabel.text isEqualToString:@"more"]){ // this means we need to expand 

     listOfSections = [[NSMutableArray alloc]init]; 
     //setting up the list of section with empty arrays 

     NSMutableArray *emptyArray = [[NSMutableArray alloc]init]; 
     for (int i = 0;i<[allDates count]; i++) { 
      [listOfSections addObject:emptyArray]; 
     } 

     //Add array of tasks here 
     [listOfSections replaceObjectAtIndex:indexPath.section withObject:[listOfSections_DataSource objectAtIndex:indexPath.section]]; 


     int tapedRow = [indexPath section]; 

     self.selectedSection = tapedRow; 

     NSMutableIndexSet *myIndexSet = [[NSMutableIndexSet alloc]init]; 
     [myIndexSet addIndex:selectedSection]; 
     [myIndexSet addIndex:selectedSectionTail]; 

     // Updating section in the tableview 
     if(selectedSectionTail!=-1) 
      [taskTable reloadSections:(NSIndexSet*)myIndexSet withRowAnimation:UITableViewRowAnimationFade]; 
     else { 
      [taskTable reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation: 
      UITableViewRowAnimationFade]; 
     } 
     //[taskTable reloadData]; 
    } 
    else{ 
    } 
    selectedSectionTail = selectedSection; 
} 

Проблема здесь в том, что: 1. Количество секций, которые показаны на экране является правильным, но когда первая ячейка похлопал , он исчезает. 2. список не расширяется при прослушивании любой из ячеек.

Пожалуйста, кто-нибудь может мне помочь? Спасибо ..

ответ

2

Этот образец может быть то, что вы ищете: http://developer.apple.com/library/ios/#samplecode/TableViewUpdates/Introduction/Intro.html

Образец вытягивает из статических данных, но вы должны быть в состоянии обновить его, чтобы использовать динамические данные из БД, а также дать задачи на дату и т.д.

+0

спасибо .. но я уже прошел через это .. он поднимает данные из списка свойств, а не из массива –

+0

@ Crazed'n'Dazed использовать .plist вы должны загрузить его с NSDictionary , и я полагаю, что NSDictionary имеет какой-то NSArray внутри приведенного примера. Вы должны проверить его снова –

+0

Также вы можете изменить образец для чтения из массива, а не из plist. – canhazbits

1

дело в том, что мне нужно было сейчас работает, так что я буду пост код здесь:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    BOOL flag = NO; 
    allDates = [[NSMutableArray alloc]init]; 

    self.date = [[NSMutableArray alloc] init]; 
    // self.date = [[NSMutableArray alloc]init]; 
    self.listOfSections_DataSource = [[NSMutableArray alloc]init]; 

    sqlite3_stmt *statement; 
    const char *dbpath = [mDatabasePath UTF8String]; 
    if (sqlite3_open(dbpath,&mDiary)== SQLITE_OK) { 
     NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM TODO"]; 
     const char *query_stmt = [selectSQL UTF8String]; 
     if (sqlite3_prepare_v2(mDiary, 
           query_stmt, -1, &statement, NULL) == SQLITE_OK) 
     { 
        while(sqlite3_step(statement) == SQLITE_ROW) 
      { 
       tempTaskName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]; 

       [allDates addObject:[[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]]; 

      //[self.date addObject:tempTaskName]; 


      } 

    } 
    sqlite3_finalize(statement); 
} 
    NSLog(@"%i",[allDates count]); 
sqlite3_close(mDiary); 
    self.date = [NSMutableArray arrayWithCapacity:[allDates count]]; 
    for(int p = 0; p < [allDates count]; p++) 
    { 
     for(int q = p+1; q < [allDates count]; q++) 
     { 
     if([allDates[p] isEqualToString:allDates[q]]) 
     { 
      flag = YES; 
      break; 

     } 
    } 
     if(flag) 
     { 
      //[self.date addObject:allDates[p]]; 
      [allDates removeObjectAtIndex:p]; 
     } 
     flag = NO; 
    } 
    // NSLog(@"%u",[self.date count]); 
    // [allDates setArray:self.date]; 
NSLog(@"allDates count%i",[allDates count]); 

     for(int x = 0;x < [allDates count];x++) 
     { 
      if (sqlite3_open(dbpath,&mDiary)== SQLITE_OK) { 
       NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM TODO"]; 
       const char *query_stmt = [selectSQL UTF8String]; 

       if (sqlite3_prepare_v2(mDiary, 
             query_stmt, -1, &statement, NULL) == SQLITE_OK){ 
      temp = [[NSMutableArray alloc]init]; 
      while(sqlite3_step(statement) == SQLITE_ROW) 
      { 
       tempTaskName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]; 
       NSLog(@"%@",tempTaskName); 

       if([[[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)] isEqualToString:allDates[x]]) 
       { 
        [self.temp addObject:tempTaskName]; 
       } 




      } 
      NSLog(@"task name%@",temp); 
      [listOfSections_DataSource addObject:temp]; 

       } sqlite3_finalize(statement); 
      } 
      sqlite3_close(mDiary); 
     } 

    //[self.listOfSections_DataSource addObject:allDates]; 

    NSMutableArray *emptyArray = [[NSMutableArray alloc]init]; 
    listOfSections = [[NSMutableArray alloc]init]; 
    for (int i = 0;i<[allDates count]; i++) { 
     [listOfSections addObject:emptyArray]; 
    } 
    self.selectedSection = -1; 
    self.selectedSectionTail = -1; 
} 

в таблице методы вид:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 


     return [listOfSections_DataSource count]; 


    } 


    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 


      if(selectedSection !=section) 
      return 1; 
     else{ 
      NSArray *array = [listOfSections objectAtIndex:section]; 

      return [array count]; 
     } 


} 



    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 

     for(int y = 0;y<[allDates count]; y++) 
     { 
      if (section == y) { 
       return allDates[y]; 
      } 
     } 
    } 
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

     static NSString *CellIdentifier = @"cell"; 

     if(self.selectedSection == indexPath.section){//this is just to check to see if this section is the one we touched 

      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
      if (cell == nil) 
      { 
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
      } 

      // cell.textLabel.text = [[listOfSections_DataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]; 
      NSArray *myArray = [listOfSections_DataSource objectAtIndex:indexPath.section];//tasks 
      NSString* myString = [myArray objectAtIndex:indexPath.row]; // get task for that row, under the date 

      cell.textLabel.text = myString; 
      return cell; 
     } 
     else{//THIS IS going to happen the first time 
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
      if (cell == nil) 
      { 
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
      } 

       cell.textLabel.text = @"more"; 

      return cell; 
     } 
    } 

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 


     UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath]; 

     //check to see if the cell is for exapnding or for selection 
     if([cell.textLabel.text isEqualToString:@"more"]){ // this means we need to expand 

      listOfSections = [[NSMutableArray alloc]init]; 
      //setting up the list of section with empty arrays 

      NSMutableArray *emptyArray = [[NSMutableArray alloc]init]; 
      for (int i = 0;i<[allDates count]; i++) { 
       [listOfSections addObject:emptyArray]; 
      } 

      //Add array of tasks here 
      [listOfSections replaceObjectAtIndex:indexPath.section withObject:[listOfSections_DataSource objectAtIndex:indexPath.section]]; 


      int tapedRow = [indexPath section]; 

      self.selectedSection = tapedRow; 

      NSMutableIndexSet *myIndexSet = [[NSMutableIndexSet alloc]init]; 
      [myIndexSet addIndex:selectedSection]; 
      [myIndexSet addIndex:selectedSectionTail]; 

      // Updating section in the tableview 
      if(selectedSectionTail!=-1) 
       [taskTable reloadSections:(NSIndexSet*)myIndexSet withRowAnimation:UITableViewRowAnimationFade]; 
      else { 
       [taskTable reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation: 
       UITableViewRowAnimationFade]; 
      } 
      //[taskTable reloadData]; 
     } 
     else{ 
     } 
     selectedSectionTail = selectedSection; 
    } 

Я знаю, что это должно быть намного лучше, но это решение сработало для меня, поэтому я решил опубликовать его.

2

JKExpandTableView является открытой библиотекой источника реализации развернутого представления таблицы (подкласс UITableView) и должен помочь вам: http://jackkwok.github.io/JKExpandTableView/

Заканчивать пример приложение.

screenshot

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