Monday, June 10, 2013

Move or Delete UiTableViewCell in iOS

In this example i will show how to move or delete cell in TableView.
First take UiTableView, allocate it datasource and delegate to File's Owner.

.h

#import <UIKit/UIKit.h>

@interface FavouriteListVC : UITableViewController
-(IBAction)btnEdit:(id)sender;
@end


.m
ViewDidLoad.


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIBarButtonItem *btn=[[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(btnEdit:)];
    btn.tag=10;
    self.navigationItem.rightBarButtonItem=btn;

}
-(IBAction)btnEdit:(id)sender
{
    int tag=[sender tag];
    if(tag==10)
    {
    [self.tableView setEditing:YES animated:YES];
    [sender setTitle:@"Done"];
        self.editing=YES;
        [sender setTag:11];
    }
    else
    {
        [self.tableView setEditing:NO animated:YES];
        [sender setTitle:@"Edit"];
        [sender setTag:10];
    }
}
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSObject *obj=[self.favList objectAtIndex:sourceIndexPath.row];
if(destinationIndexPath.row>sourceIndexPath.row)
{
    for(int x=destinationIndexPath.row;x>sourceIndexPath.row;x--)
    {
        [self.favList replaceObjectAtIndex:x-1 withObject:[self.favList objectAtIndex:x]];
    }
}
    else
    {
        for(int x=destinationIndexPath.row;x<sourceIndexPath.row;x++)
        {
            [self.favList replaceObjectAtIndex:x+1 withObject:[self.favList objectAtIndex:x]];
        }
    }
    [self.favList replaceObjectAtIndex:destinationIndexPath.row withObject:obj];
    
}
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(editingStyle==UITableViewCellEditingStyleDelete)
{
    [self.favList removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:

[NSArray arrayWithObject:indexPath]
         withRowAnimation:UITableViewRowAnimationFade];
   
}

}


No comments:

Post a Comment