Block reordering in a specific cell of a TableView
Asked Answered
G

3

8

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.

Gunnar answered 27/2, 2013 at 17:15 Comment(0)
G
12

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;

}

Gunnar answered 27/2, 2013 at 18:26 Comment(0)
B
1

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

Bangup answered 27/2, 2013 at 17:21 Comment(1)
That cell can't be reordered, but when you click at EDIT BUTTON to reorder other cells, it changes the position too... I want it static.Gunnar
S
1

SWIFT 5 CODE:

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

    if proposedDestinationIndexPath.row == 0 {
        return sourceIndexPath
    }
    
    return proposedDestinationIndexPath
}
Simplicidentate answered 12/8, 2020 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.