Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block reordering in a specific cell of a TableView

I want to block a cell to be reordered.

For example:

I have a tableview with 4 rows but don't want that the first cell can be reordered.

Is that possible?

I've tried to use:

if(indexPath.row == 0)
{
    [cell setEditing:NO animated:NO];
}

But doesn't work.

Thanks.

like image 360
Gustavo Barbosa Avatar asked Feb 27 '13 17:02

Gustavo Barbosa


3 Answers

I found the answer!

You can use the method targetIndexPathForMoveFromRowAtIndexPath from UITableViewDelegate.

-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath{
    if (proposedDestinationIndexPath.row == 0) {
        return sourceIndexPath;
    }
    return proposedDestinationIndexPath;

}

like image 145
Gustavo Barbosa Avatar answered Oct 12 '22 23:10

Gustavo Barbosa


Your UITableViewDataSource should implement -(BOOL)tableView:canMoveRowAtIndexPath: and return NO for indexPath.row == 0

- (BOOL)tableView:canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (indexPath.row != 0);
}

UITableViewDataSource documentation

like image 21
iain Avatar answered Oct 13 '22 01:10

iain


SWIFT 5 CODE:

func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {

    if proposedDestinationIndexPath.row == 0 {
        return sourceIndexPath
    }
    
    return proposedDestinationIndexPath
}
like image 37
Bandyliuk Avatar answered Oct 13 '22 01:10

Bandyliuk