Use of CollectionViewDataSource method moveItemAt for Reordering CollectionView cell In IOS (Swift 4)

Use of CollectionViewDataSource method moveItemAt for Reordering CollectionView cell In IOS (Swift 4)

In this tutorial we are study about how we can reordered the collectionView cell in collectionView. This functionality is introduced in IOS 9, And this is used by adding the gesture on collectionView. Lest go we are study about this.

addGestureRecognizer with CollectionView

First we need to add gesture (Long press gesture) with collectionView for move the collection View item. Below code is for add the Long press geture :-


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    <span class="hljs-keyword">var</span> arrayCellTitle = [<span class="hljs-type">Int</span>]()
 <span class="hljs-keyword">override</span> <span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">viewDidLoad</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">super</span>.viewDidLoad()
        <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>...<span class="hljs-number">20</span> {
            arrayCellTitle.append(value)
        }
        configureCollectionView()
    }
   
<span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">configureCollectionView</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">let</span> longPressGesture = <span class="hljs-type">UILongPressGestureRecognizer</span>(target: <span class="hljs-keyword">self</span>, action: #selector(actionLongPressGesture(gesture:)))
        <span class="hljs-keyword">self</span>.collectionView.addGestureRecognizer(longPressGesture)
    }
   
    <span class="hljs-preprocessor">@objc</span> <span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">actionLongPressGesture</span><span class="hljs-params">(gesture: UILongPressGestureRecognizer)</span></span> {
       
        <span class="hljs-keyword">switch</span>(gesture.state) {
        <span class="hljs-keyword">case</span> .began:
            <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> selectedIndexPath = <span class="hljs-keyword">self</span>.collectionView.indexPathForItem(at: gesture.location(<span class="hljs-keyword">in</span>: <span class="hljs-keyword">self</span>.collectionView)) <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">break</span>
            }
            collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
        <span class="hljs-keyword">case</span> .changed:
            collectionView.updateInteractiveMovementTargetPosition(gesture.location(<span class="hljs-keyword">in</span>: gesture.view!))
        <span class="hljs-keyword">case</span> .ended:
            collectionView.endInteractiveMovement()
        <span class="hljs-keyword">default</span>:
            collectionView.cancelInteractiveMovement()
        }
    }
  1. beginInteractiveMovementForItem(at indexPath: IndexPath) -> Its initiates the interactive movement of the cell at the specified index path.
  2. updateInteractiveMovementTargetPosition(_:) -> Update the item position whith In collection view and according to getsure position
  3. endInteractiveMovement()-> Its use for end interactive movement of item. After completed the long press gesture effect.
  4. cancelInteractiveMovement()-> Ends interactive movement tracking

 

Now, When we are move the collectionView item position we Are getting the call back in collectionViewDataSource method “moveItemAt”. We can manage here our data according to updated cell. Below are example of UICollectionViewDataSource “moveItemAt” method :


1
2
3
4
<span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">collectionView</span><span class="hljs-params">(<span class="hljs-number">_</span> collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)</span></span> {
        <span class="hljs-keyword">let</span> value = arrayCellTitle.remove(at: sourceIndexPath.item)
        arrayCellTitle.insert(value, at: destinationIndexPath.item)
    }

Handle Cell is move or not

In UICollectionViewDataSource provide a function “canMoveItemAt” for handle the item is move or not. In this method we need to return bool value for item is move or not.
Example :-


1
2
3
4
5
6
7
<span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">collectionView</span><span class="hljs-params">(<span class="hljs-number">_</span> collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath)</span></span> -&gt; <span class="hljs-type">Bool</span> {
        <span class="hljs-keyword">if</span> indexPath.row % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
        }
    }

How to move item at particular indexPath

In UICollectionViewDelegate provide functions “targetIndexPathForMoveFromItemAt” for handle item target indexPath.


1
2
3
4
5
6
7
8
9
<span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">ViewController</span>: <span class="hljs-title">UICollectionViewDelegate</span> </span>{
<span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">collectionView</span><span class="hljs-params">(<span class="hljs-number">_</span> collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath)</span></span> -&gt; <span class="hljs-type">IndexPath</span> {
<span class="hljs-keyword">return</span> <span class="hljs-type">IndexPath</span>(item: <span class="hljs-number">5</span>, section: <span class="hljs-number">0</span>)
}
<span class="hljs-comment">//customize the content offset to be applied during transition or update animations</span>
<span class="hljs-func"><span class="hljs-keyword">func</span> <span class="hljs-title">collectionView</span><span class="hljs-params">(<span class="hljs-number">_</span> collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint)</span></span> -&gt; <span class="hljs-type">CGPoint</span> {
<span class="hljs-keyword">return</span> <span class="hljs-type">CGPoint</span>(x: <span class="hljs-number">100</span>, y: <span class="hljs-number">100</span>)
}
}

 




You can download the complete Sample project here…

Related Post

First Java Program First Java Program NOTE: You need to have java installed on your system. Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. W...
Variables Variables A variable is a named location in memory that is used to hold a value that can be modified by the program. All variable must be declared be...
New features in XCode 10 Supported Configurations Xcode 10 beta requires a Mac running macOS 10.13.4 or later Xcode 10 beta includes SDKs for iOS 12, watchOS 5, macOS ...
Create Firebase single Page Website Create firebase single page Website tutorial In this tutorial we are study how to create single page website by the use of firebase hosting its very ...
Strings String can be represented as a single-dimensional character type array. Strings in C are group of characters, digits, and symbols enclosed in quotatio...
Setting Class Path for Java Setting Class Path for Java In this tutorial we are study how we can set the java JDK class path. Java is an open source software, it is is freely...

Leave a Reply

Your email address will not be published. Required fields are marked *