Многоуровневая UITableView?

Нужно сделать много уровненую таблицу. К примеру в начале у нас есть всего 3 ячейки
cc9f19a769b613a2fcaa7337ab02c1fa.png


Тапая по первой у нас добавятся ячейки второго уровня 1d09805ad46be36022dc59a7bb3b88f1.png


И дальше 3го уровня


Я понимаю, что это делается простым insertRowsAtIndexPaths Но у меня данные берутся из разных массивов. Я так думаю нужно использовать какие то состояния для каждого случая. Но не могу понять как. Может кто то делал что то подобное? Поделитесь сниппетами ;)
  • Вопрос задан
  • 3453 просмотра
Решения вопроса 1
@frantic
Делал подобное.

На входе миссив (NSArray), у каждого элемента есть уровень. Пробегал по массиву и создавал вьювы со сдвигом влево. Потом это все пихал в UITableViewCell.

-(void) flateCommentsData:(NSArray *)_data withLevel:(NSInteger)level
{
  NSEnumerator * dataEnum = [_data objectEnumerator];
  
  NSDictionary * commentData;
  
  while (commentData = [dataEnum nextObject])
  {
    SModelComment * commentModel = [[SModelComment alloc]init];
    
    [commentModel set:@"id" withValue:[commentData objectForKey:@"id"]];
    [commentModel set:@"text" withValue:[commentData objectForKey:@"text"]];
    [commentModel set:@"userId" withValue:[commentData objectForKey:@"userId"]];
    [commentModel setLevel:level];
    
    CGRect cellRect = CGRectMake(commentModel.level*5, 0, 320 - commentModel.level*5, 0);
    UIView * cellView = [[UIView alloc] initWithFrame: cellRect];
    
    //add avatar
    SModelUser * user = [SModelUserPeer loadObjectById:[commentModel get:@"userId"]];
    UIImageView * avatarView = [[UIImageView alloc] initWithImage: user.smallAvatar.image ];
    avatarView.frame = CGRectMake(5, 7, 35, 35);
    [cellView addSubview:avatarView];
    
    //add username
    UILabel * usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 5, cellRect.size.width - 75, 20)];
    usernameLabel.font = [UIFont boldSystemFontOfSize:14.0];
    usernameLabel.text = [user get:@"fullName"];
    [cellView addSubview:usernameLabel];
        
    //add text
    CGRect cellTextRect = CGRectMake(45, 25, cellRect.size.width - 75, 0);
    UILabel * cellTextLabel = [[UILabel alloc] initWithFrame:cellTextRect];
    cellTextLabel.text = [commentModel get:@"text"];
    cellTextLabel.font = [UIFont systemFontOfSize:12.0];
    cellTextLabel.numberOfLines = 0;
    [cellTextLabel sizeToFit];
    cellTextLabel.backgroundColor = [UIColor whiteColor];
    [cellView addSubview:cellTextLabel];
    
    
    CGRect textFrame = cellTextLabel.frame;
    textFrame.size.height = textFrame.size.height + 10 + usernameLabel.frame.size.height
    ;
    textFrame.size.height = textFrame.size.height > 50 ? textFrame.size.height : 50;

    cellRect.size.height = textFrame.size.height;
    cellView.frame = cellRect;
        
    NSMutableDictionary * item = [[NSMutableDictionary alloc] initWithCapacity:2];
    [item setObject:cellView forKey:@"view"];
    [item setObject:commentModel forKey:@"model"];
    
    [commentsList addObject:item];
    
    if ([commentData objectForKey:@"childs"])
    {
      [self flateCommentsData:[commentData objectForKey:@"childs"] withLevel:level+1];
    }
  }
}


потом

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSDictionary * item = [commentsList objectAtIndex:indexPath.row]; 
	UIView * cellView   = [item objectForKey:@"view"];
	SModelComment * commentModel = [item objectForKey:@"model"];
	
	NSString * CellIdentifier = [NSString stringWithFormat:@"comment_cell_%d", [commentModel get:@"id"]];
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	[cell.contentView addSubview:cellView];

    return cell;	
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы