Monday 29 August 2011

Deletion of Data displaying in TableView


This blog describe an easy method to delete values showing in the list without adding some sort of buttons .

In your ViewController.h file

IBOutlet UITableView *countriesTableView;
UIBarButtonItem *donebutton;

-(void)editClicked;
-(void)doneClicked;


In your ViewController.m file

- (void)viewDidLoad {
donebutton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(editClicked) ];
self.navigationItem.rightBarButtonItem = donebutton;
}

-(void)editClicked
{
self.countriesTableView.editing=YES;
donebutton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(doneClicked)] ;
self.navigationItem.rightBarButtonItem = donebutton;

}

-(void)doneClicked
{
self.countriesTableView.editing=NO;
donebutton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(editClicked) ];
self.navigationItem.rightBarButtonItem = donebutton;

}

countriesArray is my array which holds the values that will be displayed (you can write array of your own requirement)

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


if([self.countriesArray count]>0)
{
return [self.countriesArray count];
}
else {
return 0;
}

}

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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

cell.textLabel.text=[self.countriesArray objectAtIndex:indexPath.row];

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tbleView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

if (tbleView.editing == NO || !indexPath)
return UITableViewCellEditingStyleNone;
if (tbleView.editing) {
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone;
}



-(void)tableView:(UITableView *)tbleView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
rowNo=indexPath.row;
[self.countriesArray removeObjectAtIndex:indexPath.row];
[countriesTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}


Happy Coding!!!

No comments:

Post a Comment