Sunday, March 17, 2013

Drag Table Row any where withing UitableView in ios

In this Example i am showing you how you can drag row within TableView.

Following Step.

-- ViewController.h

-->
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
@property (retain, nonatomic) IBOutlet UITableView *dragTableview;
@property(retain,nonatomic)NSMutableArray *aryData;
@end

 
Here aryData contain list of Data to display in UiTableView.


-- ViewController.m

-->
@synthesize aryData,dragTableview=_dragTableview;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.aryData=[[NSMutableArray alloc ] initWithObjects:@"Section1-row1",@"Section2-row2",@"Section2-row3", nil];
    [self.dragTableview setEditing:YES];
    self.title=@"DragTableRow";
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0)
            return 1;
    else
        return 3;
   
    //return self.aryData.count;
}

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

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section==0)
        return @"Section1";
    else
        return @"Section2";
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cell=@"Cell";
    UITableViewCell *tblcell=[tableView dequeueReusableCellWithIdentifier:cell];
    if(tblcell==nil)
    {
        tblcell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell];
       
    }
    if(indexPath.section==0)
    {
    tblcell.textLabel.text=[self.aryData objectAtIndex:indexPath.row];
    tblcell.backgroundColor=[UIColor grayColor];
    }
    else
    {
       
        tblcell.textLabel.text=[self.aryData objectAtIndex:indexPath.row];
    tblcell.backgroundColor=[UIColor greenColor];
    }
    return tblcell;
}

-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
//return destinationIndexPath;
    NSString *item = [[self.aryData objectAtIndex:sourceIndexPath.row] retain];
    [self.aryData removeObject:item];
    [self.aryData insertObject:item atIndex:destinationIndexPath.row];
    [item release];
}

-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  YES;
}


To make row to move, set Uitableview Editable mode to True
Here in MoveRowAtIndexPath Delegate Method i remove and add item on particular position.

OutPut : For Same View set UiTableView Style to "Grouped"






 
 


No comments:

Post a Comment