Ir para conteúdo
  • Cadastre-se

Custom Table View Cell


Posts Recomendados

Ola a todos,

Estou criando uma TableView onde quero que as cells sejam exclusivamente Custom TableViewCells, a partir de um padrao construido no Interface Builder. Criei a cell e no cellForRowAtIndexPath eu faço

return customCell;

Mas a table view nao é totalmente populada. Apenas a ultima cell visivel é populada com o conteudo definido pelo interface builder. Eis o codigo utilizado:

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

    static NSString *CellIdentifier = @"customCell";

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

	customCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (customCell == nil) {
		customCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
	}

	cell.textLabel.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yellowColor.png"]];

    // Configure the cell...
	eventoCellTextLabel.text = @"Evento";

    return customCell;
}

Mas nada aparece. As cells estao la, pois posso ate clicar nelas, mas o conteudo definido no IB nao...

Agradeço muito a quem puder ajudar!

Editado por Gabriel Vincent
Link para o comentário
Compartilhar em outros sites

  • Respostas 2
  • Criado
  • Última resposta

Top Postadores Neste Tópico

faz algo assim ...


//Crie uma tag única para cada objeto que será manipulado.
    static NSUInteger const kNameLabelTag = 2;

    //Declaração das Labels.
    UILabel *nameLabel = nil;

	//Identidade de cada Cell.
    static NSString *CellIdentifier = @"LocationCell";

	//Cria uma Cell com a identidade e atribui ao ponteiro uma celula com a identidade usada.  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

	if (cell == nil) {
        // Não Tem Celulas na tela para reuso, então criamos.
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:CellIdentifier];

        //Local na celula onde vai ser iniciado o frame.
        nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 3, 190, 20)];
        nameLabel.tag = kNameLabelTag;
        nameLabel.font = [UIFont boldSystemFontOfSize:14];
        nameLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
		//adiciona ao subview.
        [cell.contentView addSubview:nameLabel];
    } else {
        // tem uma célula na tela disponível para reuso
        nameLabel = (UILabel *)[cell.contentView viewWithTag:kNameLabelTag];
    }

	//Recupere o dado da celula que vai exibir …
    Location *managedObject = (Location *)[self.fetchedResultsController objectAtIndexPath:indexPath];

    //atribua o valor ao label custom.
    nameLabel.text = [NSString stringWithFormat:@"%@%@", @"", managedObject.name];

    //Adiciona uma setinha em cada tela pra dizer ao usuário que uma ação pode ser tomada.
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;

para muitos labels ou quaisquer objetos na custom cell o melhor é atribuir tags a cada um, assim vc tem como identificar qual objeto é qual quando for atribuir um ponteiro para cada objeto na célula.

obs.: estou usando o ARC do IOS 5 sdk, adicione os autorelease e releases necessários para SDK mais antigos. ;)

Editado por Artur Felipe
Link para o comentário
Compartilhar em outros sites

  • 2 semanas depois...

Boa Noite, espero que ajudar a solucionar o seu problema, caso ainda não o tenha. Tenta fazer os seguinte:

Para facilitar crie, além do .xib, o .h e o .m da sua célula.

Escreve o código abaixo na tabela onde queres mostrar a nova célula.


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"nomeDaClasseDaCustomCell";

nomeDaClasseDaCustomCell *cell = (nomeDaClasseDaCustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cellItens == nil) {
NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"nomeDaClasseDaCustomCell" owner:self options:nil];

cellItens = [nibs objectAtIndex:0];

}
//Configura a tua célula
cell.textLabel.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yellowColor.png"]];
cell.propriedadeLabelDaClasseCuston.text = @"Evento";

return cell;
}
[/CODE]

Também não esquece de implementar o código:

[CODE]

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return valorDoHeightDaCelulaCustonNoInterfaceBuilder;
}
[/CODE]

Outra coisa chata, que as vezes esqueço, é setar no .xib da classe Custon o .h que criastes, assim como o Identifier no Atributes Inspector. E outro fator é o de fazer a conexão dos teus IBOutlets com os Objects e não com o File's Owner.

Espero ter ajudado, boa sorte! ;)

Link para o comentário
Compartilhar em outros sites

Participe do debate

Você pode postar agora e se registrar depois. Se você tem uma conta, entre agora para postar com ela.

Visitante
Responder este tópico…

×   Você colou conteúdo com formatação.   Remover formatação

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Limpar editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Quem Está Navegando   0 membros estão online

    • Nenhum usuário registrado visualizando esta página.



  • Estatísticas do Fórum

    • Total de Tópicos
      56.5k
    • Total de Posts
      466.2k
×
×
  • Criar Novo...