Apostila iPhone - Table View - Criando Classe
sábado, setembro 4th, 2010Para criar uma classe, de um click na pasta do grupo CustomCell e em File / File New.


Vamos selecionar Cocoa Touch Class / Objective-C class.
Ao escolher estas opções, o XCode irá perguntar qual o nome que deseja colocar na sua classe. Vamos colocar CustomCell. Observe que quando colocar o nome da classe, você estará criando o header do arquivo, e se observar melhor, perceberá que existe a opção de criar automaticamente a implementação (“.m”).
Agora vamos implementar de fato estas classes. No arquivo CustomCell.h, digite o seguinte código:
@interface CustomCell : UITableViewCell
{
BOOL checked;
NSString *title;
UIButton *checkButton;
}
@property (nonatomic, retain) NSString *title;
@property (nonatomic, assign) BOOL checked;
- (void)checkAction:(id)sender;
@end
No arquivo CustomCell.m digite o seguinte código:
@implementation CustomCell
@synthesize checked, title;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
{
self.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
// cell’s title label
self.textLabel.backgroundColor = self.backgroundColor;
self.textLabel.opaque = NO;
self.textLabel.textColor = [UIColor blackColor];
self.textLabel.highlightedTextColor = [UIColor whiteColor];
self.textLabel.font = [UIFont boldSystemFontOfSize:18.0];
// cell’s check button
checkButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
checkButton.frame = CGRectZero;
checkButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
checkButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[checkButton addTarget:self action:@selector(checkAction: ) forControlEvents:UIControlEventTouchDown];
checkButton.backgroundColor = self.backgroundColor;
[self.contentView addSubview:checkButton];
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
CGRect contentRect = [self.contentView bounds];
CGRect frame = CGRectMake(contentRect.origin.x + 40.0, 8.0, contentRect.size.width, 30.0);
self.textLabel.frame = frame;
// layout the check button image
UIImage *checkedImage = [UIImage imageNamed:@"checked.png"];
frame = CGRectMake(contentRect.origin.x + 10.0, 12.0, checkedImage.size.width, checkedImage.size.height);
checkButton.frame = frame;
UIImage *image = (self.checked) ? checkedImage: [UIImage imageNamed:@"unchecked.png"];
UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
[checkButton setBackgroundImage:newImage forState:UIControlStateNormal];
}
- (void)dealloc
{
[checkButton release];
[title release];
[super dealloc];
}
// called when the checkmark button is touched
- (void)checkAction:(id)sender
{
// note: we don’t use ’sender’ because this action method can be called separate from the button (i.e. from table selection)
self.checked = !self.checked;
UIImage *checkImage = (self.checked) ? [UIImage imageNamed:@"checked.png"] : [UIImage imageNamed:@"unchecked.png"];
[checkButton setImage:checkImage forState:UIControlStateNormal];
}
Agora, vamos terminar a nossa nova implementação.
Diferentemente do tópico anterior, vamos conhecer mais alguns métodos que podem (e neste caso devem) ser implementados. Porém antes, vamos digitar o seguinte código no arquivo CellsViewController.h:
@interface CellsViewController : UIViewController
<UITableViewDataSource, UITableViewDelegate>
{
NSMutableArray *computers;
}
@property (nonatomic, retain) NSMutableArray *computers;
@end
Vamos ver um novo componente, o NSMutableArray. Este componente tem o mesmo comportamento do NSArray, porém este componente permite mutação, ou seja, conseguimos colocar praticamente qualquer tipo de informação neste array.
No arquivo CellsViewController.m insira o seguinte código:
#import “CellsViewController.h”
#import “CustomCell.h”
#import “CellsAppDelegate.h”
@implementation CellsViewController
@synthesize computers;
- (void)viewDidLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:@”Data” ofType:@”plist”];
self.computers = [NSMutableArray arrayWithContentsOfFile:path];
}
- (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;
self.computers = nil;
}
- (void)dealloc {
[computers release];
[super dealloc];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.computers count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// find the cell being touched and update its checked/unchecked image
CustomCell *targetCustomCell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath];
[targetCustomCell checkAction:nil];
// don’t keep the table selection
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// update our data source array with the new checked state
NSMutableDictionary *selectedItem = [self.computers objectAtIndex:indexPath.row];
[selectedItem setObject:[NSNumber numberWithBool:targetCustomCell.checked] forKey:@”checked”];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCustomCellID = @”MyCellID”;
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = (CustomCell *)[[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
}
NSDictionary *item = [computers objectAtIndex:indexPath.row];
NSString* title = [item objectForKey:@"text"];
cell.title = title;
cell.textLabel.text = title;
cell.checked = [[item objectForKey:@"checked"] boolValue];
return cell;
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
// called when the accessory view (disclosure button) is touched
CustomCell *cell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath];
CellsAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:
cell.title, @"text",
[NSNumber numberWithBool:cell.checked], @”checked”,
nil];
[appDelegate showDetail:infoDict];
}
@end
Observe o método viewDidLoad. Neste momento estamos populando nosso dicionário com o arquivo XML que criamos anteriormente. Alguns métodos vamos estudar no próximo tópico, quando vamos dar ações nas nossas células. Por enquanto compile e execute este código.
Exercício
- Modifique o projeto iReceita. Coloque a entrada de dados por meio de XML e modifique a configuração da célula e insira um botão que será para determinar a ação da mesma.
(@AdemarVarela)









