2013-08-05 3 views
0

iOS 기본 앱 개발 팀에서 여름 방학 중입니다. 그들은 섹션을 사용하지 않고 테이블 뷰에서 셀을 제거/삽입하는 작업을 내게주었습니다. 누군가가 코드를보고 나를 도우려고하면 이드에게 많은 고마움을 전할 수 있다면 고심하고있다. 일부 제거 및 실종 상태가 발생하지만 일관성을 유지하지 못하고 있으며 이미 보이는 셀을 추가하고 있습니다. (한 번 내가 행을 삽입 의미에서 일관성, 행 3 지금 내 모듈로 연산이 던져진 도착 5 행,된다.섹션을 사용하지 않는 아코디언 스타일 표보기

을 나는 어떤 조언/도움을 많이 주시면 감사하겠습니다 있도록 목표 다 아주 새로운 오전.

@implementation MasterViewController 


NSMutableArray * levels; 
NSMutableArray * array; 
NSMutableIndexSet * expandedSections; 
NSMutableDictionary * dict; 

-(BOOL) loadFiles{ 
    // NSFileManager * fileManager = [NSFileManager defaultManager]; 
    if (!expandedSections) { 
     expandedSections = [[NSMutableIndexSet alloc]init]; 
    } 

    array = [[NSMutableArray alloc]init]; 
    levels = [[NSMutableArray alloc]init]; 

    for (int i=0; i<20; i++) { 
     NSString * temp = [[NSString alloc]initWithFormat:@"This is row : %i ", i]; 
     [array addObject:temp]; 
    } 
    for (int i=0; i<20; i++) { 
     NSNumber * temp = [[NSNumber alloc]initWithInt:i]; 
     [levels addObject:temp]; 
    } 


    dict = [[NSMutableDictionary alloc]initWithObjects:array forKeys:levels]; 
    NSLog(@"TEST: %@", [dict objectForKey:[levels objectAtIndex:1]]); 

    return YES; 
} 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     self.title = NSLocalizedString(@"Master", @"Master"); 
    } 
    return self; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self loadFiles]; 

// Do any additional setup after loading the view, typically from a nib. 
    self.navigationItem.leftBarButtonItem = self.editButtonItem; 

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)]; 
    self.navigationItem.rightBarButtonItem = addButton; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (void)insertNewObject:(id)sender { 
    if (!_objects) { 
     _objects = [[NSMutableArray alloc] init]; 
    } 
    [_objects insertObject:[NSDate date] atIndex:0]; 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
} 

#pragma mark - Table View 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if ([expandedSections containsIndex:section]) { 
     return [array count] +2; 
    } 
    return [array count]; 
} 

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 

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

    if (!(indexPath.row %3)==0) { 
     cell.textLabel.text = [dict objectForKey:[levels objectAtIndex:indexPath.row]]; 
     [cell setIndentationLevel:2]; 
     cell.accessoryType = UITableViewCellAccessoryNone; 
     cell.accessoryView = nil; 
    } else { 
     cell.textLabel.text = [dict objectForKey:[levels objectAtIndex:indexPath.row]]; 
     [cell setIndentationLevel:0]; 
    } 

    return cell; 
} 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { 
    // Return NO if you do not want the specified item to be editable. 
    return YES; 
} 

- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     [_objects removeObjectAtIndex:indexPath.row]; 
     [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } else if (editingStyle == UITableViewCellEditingStyleInsert) { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. 
    } 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (!self.detailViewController) { 
     self.detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil]; 
    } 
    BOOL currentlyExpanded = [expandedSections containsIndex:indexPath.row]; 
    //[tableView deselectRowAtIndexPath:indexPath animated:YES]; 
    NSLog(@"CurrentlyExpanded : %d", currentlyExpanded); 
    NSLog(@"TEST: %@", [dict objectForKey:[levels objectAtIndex:indexPath.row ]]); 

    if ((indexPath.row %3)==0) { 
     // only first row toggles exapand/collapse 
     [tableView deselectRowAtIndexPath:indexPath animated:YES]; 

     NSInteger section = indexPath.section; 
     BOOL currentlyExpanded = [expandedSections containsIndex:section]; 
     NSInteger rows; 

     NSMutableArray *tmpArray = [NSMutableArray array]; 

     if (currentlyExpanded) { 
      rows = 2; 
      [expandedSections removeIndex:section]; 
     } else { 
      [expandedSections addIndex:section]; 
      rows = 2; 
     } 

     for (int i=indexPath.row+1; i<=(indexPath.row + rows); i++) { 
      NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i 
                  inSection:section]; 
      [tmpArray addObject:tmpIndexPath]; 
     } 

     if (currentlyExpanded) { 
      [tableView deleteRowsAtIndexPaths:tmpArray 
          withRowAnimation:UITableViewRowAnimationTop]; 
     } else { 
      [tableView insertRowsAtIndexPaths:tmpArray 
          withRowAnimation:UITableViewRowAnimationTop]; 
     }  
    } 
    if ((indexPath.row %3)>0) { 
     NSDate *object = _objects[indexPath.row]; 
     self.detailViewController.detailItem = object; 
     [self.navigationController pushViewController:self.detailViewController animated:YES]; 
    } 
} 

@end 
+0

첫 번째 '정적있는 NSString * CellIdentifier = @ "셀";' 사용해야하는이 : 당신은 대신이 줄을 당신의 세포를 식별해야 '는 NSString * CellIdentifier = [있는 NSString stringWithFormat : @ "셀 % d 개, % D ", indexPath.row, indexPath.section]; UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier : CellIdentifier]; ' 스크롤 할 때 셀이 엉망이되기 때문입니다. – Laszlo

+0

섹션없이이 작업을 수행해야한다면이 코드의 섹션을 사용하는 이유는 무엇입니까? – rdelmar

+0

필자는 메인 섹션 인 1 섹션만으로이 작업을 수행해야하며, 어떻게해야하는지 시각화하는 데 어려움을 겪고 있습니다. – Busturdust

답변

0

TLIndexPathTools을보세요. 이렇게 동적 테이블을 만드는 것이 매우 간단하며, 일괄 처리를 계산하고 수행하는 모든 작업을 수행합니다. Outline sample project을 실행 해보십시오. 섹션을 사용하지 않고 확장 가능한 트리를 작성하는 방법을 보여줍니다. 2 레벨 트리를 구축하면 필요한 것을 얻을 수 있습니다.

관련 문제