UITableView: how to disable dragging of items to a specific row?

Viewed 12044

I have a UITableView with draggable rows and I can add/remove items. The datasource is a NSMutableArray.

Now, if I move the row with "Add new functionality" the app crashes because the dataSource is smaller since such row has not been added yet.

So I've modified this code:

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
        if (indexPath.row >= [dataList count]) return NO;
        return YES;
    }

And now I can't move it anymore. However I can still move the other rows after such row and consequently the code crashes.

How can I solve this ? Is there a way to disable the dragging "to" specific rows and not only from ?

thanks

5 Answers

Following is the example to restrict drag and drop to 0th index of 1st section UICollectionView:

func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {

    if session.localDragSession != nil {
        // Restricts dropping to 0th index
        if destinationIndexPath?.row == 0 {
           return UICollectionViewDropProposal(operation: .forbidden) 
        }

        if collectionView.hasActiveDrag {
            return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
        } else {
            return UICollectionViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath)
        }
    }        
}

func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    // Prevents dragging item from 0th index
    if indexPath.row == 0 {
        return [UIDragItem]() // Prevents dragging item from 0th index
    }

    let item = self.yourArray[indexPath.row]
    let itemProvider = NSItemProvider(object: item)
    let dragItem = UIDragItem(itemProvider: itemProvider)
    dragItem.localObject = item
    return [dragItem]
}       

Following is the working solution for disable row from moving.

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        if indexPath.row == 0{//specify your indexpath row here....
            return false
        }else{
            return true
        }
        
    }
Related