terça-feira, 15 de março de 2011

App - Criando uma tabela com três celulas

Nesse artigo mostrarei como criar uma tabela com três celulas, é para usuário mais avançados, vou mostrar somente como posicionar no arquivo xib e o código usado. Irei preencher o conteúdo das céluas usando um array. Usei a documentação da Apple no iOS Dev Center como fonte, vistou eu estar construindo um app e ter surgido essa dúvida.

Abra o Xcode, crie um novo projeto usando o template View-based Application:



Clique no botão Choose... e salve como TabelaExemplo3cell.


Agora dê dois clique em TabelaExemplo3cell.xib para abrir no Interface Builder, verá então nossa TableView aberta, vamos então criar agora três células que serão exibidas por nossa tabela, e cada célula ficará em uma seção.
Na Library procure por Table View Cell e arrasta para a janela onde se pode ver o TableViewController.xib, a janela onde se vê o File's Owner. Arraste três células, ficará como na imagem abaixo:


Dê dois clique na primeira célula e ela aparecerá como abaixo:

Como vê, a célula é uma subclasse de UIView e logo podemos inserir qualquer outro componente nela. Na Library arraste uma Label para a célula e deixe como abaixo, faça o mesmo com as outras duas células só incrementando a numeração:


Aproveite e conecte a tabela com o delegador em File's Owner:


Salve e volte para o Xcode, temos que fazer adições de código nos arquivos.
Em TabelaExemplo3cell.h, o arquivo de cabeçalho deixe o código como abaixo:


#import <UIKit/UIKit.h>

@interface TabelaExemplo3cell : UIViewController<UITableViewDelegate,UITableViewDataSource> {
NSArray *listData;
UITableViewCell *cell0;
UITableViewCell *cell1;
UITableViewCell *cell2;

}
@property(nonatomic,retain) NSArray *listData;
@property(nonatomic,retain)IBOutlet UITableViewCell *cell0;
@property(nonatomic,retain)IBOutlet UITableViewCell *cell1;
@property(nonatomic,retain)IBOutlet UITableViewCell *cell2;

@end

Veja que declarei três propriedades, cada uma representando uma célula, cada célula é um UITableViewCell.

O listData conterá nos nomes das seções.

Volte ao Interface Builder e conecte as saídas a cada uma das células criadas anteriormente.
Salve e volte ao Xcode, agora temos o seguinte código no nosso arquivo :



#import "TabelaExemplo3cell.h"
@implementation TabelaCellViewController
@synthesize listData;@synthesize cell0;@synthesize cell1;@synthesize cell2;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSArray *array = [[NSArray alloc] initWithObjects:@"Seção 1",@"Seção 2",@"Seção 3",nil];self.listData = array;
[array release];
    [super viewDidLoad];}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 1;

}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger) section{
return[listData objectAtIndex:section];
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
return cell0;}
if (indexPath.section == 1) {
return cell1;}
if (indexPath.section == 2) {
return cell2;}


}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 70;}


- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)dealloc {
[cell0 release];[cell1 release];[cell2 release];[listData release];    [super dealloc];
}
@end

No método viewDidLoad preparamos nosso array com os nomes das seções. Alocamos e depois liberamos o objeto.

Em - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { indicamos quantas seções existem, no caso 3.


Em -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ indicamos quantas fileiras existem em cada seção, nesse caso somente 1.


Em -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger) section{
return[listData objectAtIndex:section];
} passamos para o delegador o título de cada seção, lembra do array que alocamos? Assim a seção que tem indice 0 se chamará Seção 1 e assim por diante dependendo do que colocamos no nosso array.

Em -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPat passamos nossas células criadas no nib, no código que vem abaixo indicamos qual célula irá em cada seção, assim a célula 1 irá na seção 0 e assim por diante.


Com esse método, -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath apenas passo a altura da célula na tabela.

E no final apenas liberamos os objetos alocados.

Compilado nosso app ficará assim:











Nenhum comentário:

Postar um comentário