Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView, how to prevent one cell from being moved

I recently study collection view. I need to let some cells fix in their own index path, which mean they should not be exchanged by others and not be dragged. I now can use *- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath )indexPath to prevent them from dragging. I cannot prevent them from being exchanged by other cells.

Any one meet same issue?

Thanks

like image 634
Ken Chen Avatar asked Nov 28 '17 09:11

Ken Chen


People also ask

What is the difference between Uitableview and UICollectionView?

Tableiw is a simple list, which displays single-dimensional rows of data. It's smooth because of cell reuse and other magic. 2. UICollectionView is the model for displaying multidimensional data .

How do I remove cells from collectionView?

Build and Run the project and select the Edit Button. Select a few cells and press the Trash button to remove the items.

What is UICollectionView flow layout?

Overview. A flow layout is a type of collection view layout. Items in the collection view flow from one row or column (depending on the scrolling direction) to the next, with each row containing as many cells as will fit. Cells can be the same sizes or different sizes.


2 Answers

func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
    if proposedIndexPath.row == data.count {
        return IndexPath(row: proposedIndexPath.row - 1, section: proposedIndexPath.section)
    } else {
        return proposedIndexPath
    }
}
like image 77
Sharad Paghadal Avatar answered Oct 13 '22 01:10

Sharad Paghadal


I found that when I used iOS 11+ drag and drop, targetIndexPathForMoveFromItemAt wouldn't get called. Implementing this method forbids the item from being dropped where I don't want it:

func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
    // disallow dragging across sections
    guard let sourcePath = session.items.first?.localObject as? IndexPath,
        let destPath = destinationIndexPath,
        sourcePath.section == destPath.section
        else {
            return UICollectionViewDropProposal(operation: .forbidden)
    }
    return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}

Note that I stored the source index path in localObject when the drag started, because I couldn't find a way to get this information otherwise.

like image 23
bugloaf Avatar answered Oct 13 '22 01:10

bugloaf