Luong Nhu Toan
Luong Nhu Toan

Reputation: 55

Custom moving tableview cell: How to always keep first cell at top of UITableView when "moveRowAtIndexPath"

I need to keep my first cell always located at top of tableview when i move others cell.I spent a lot of time and many ways button i haven't figure out that how to solve this problem. This is my code:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     //...do something to custom first cell design from xib file

     //...do some thing to custom normal cells(cells at below of first cell)

    [firstcell setEditing:NO animated:YES];
    firstcell.userInteractionEnabled=NO;

     if (indexPath.row==0)
    {
        return firstcell;
    }
    else
    {
        return cell;
    }
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) // Don't move the first row
        return NO;
    return YES;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    // i just change datasource for tableview at here
}

And there is my tableview when I move cell (normal cell).

I wanna keep first cell (blue cell) always be at top and not be interact by others cell.

Upvotes: 1

Views: 559

Answers (1)

rmaddy
rmaddy

Reputation: 318854

You need to implement one more delegate method:

- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
    if (proposedDestinationIndexPath.row == 0) {
        // Don't allow a row to be moved to the first row position
        return [NSIndexPath indexPathForRow:1 inSection:0];
    } else {
        return proposedDestinationIndexPath;
    }
}

This code assume you only have one section in your table view.

The point of this method is to tell the table view that if the proposed destination for the row being moved isn't appropriate, the returned value should be used. As written here, any attempt to move a row to the top will result in it being moved just below the top row.

Upvotes: 3

Related Questions