UITableView Long Press gesture

Source: Internet
Author: User

Directory:

    • What do you need?
    • How to do?
    • How to use it on Uicollectionview?
    • Go?

This Cookbook-style tutorial describes how to move a cell in a table view by long-press gestures, just like Apple's own weather App.

You can add to your project directly from this article, or add it to starter project that I created for you, or download the complete example project for this article.

What do you need?
    • Uilonggesturerecognizer
    • UITableView (can be replaced with Uicollectionview)
    • Uitableviewcontroller (can be substituted with Uiviewcontroller or Uicollectionviewcontroller)
    • 5 minutes.
How to do?

First, add one to Table View UILongGestureRecognizer . Can be added in the method of the table view controller viewDidLoad .

123 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]  initWithTarget:self action:@selector(longPressGestureRecognized:)];[self.tableView addGestureRecognizer:longPress];

The reporter adds an action method for gesture recognizer. The method should first obtain the position of the long press in the table view, and then find the index of the cell corresponding to the location. Remember: The index path obtained here may be nil (for example, if the user is pressed on the section header of Table view).

12345678910 - (IBAction)longPressGestureRecognized:(id)sender {  UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;  UIGestureRecognizerState state = longPress.state;   CGPoint location = [longPress locationInView:self.tableView];  NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];  // More coming soon...}

Then you need to deal with the UIGestureRecognizerStateBegan branch. If you get to a valid index path (non-nil), get the corresponding UITableViewCell one and use a helper method to get the snapshot view of the table view cell. Then add the snapshot view to the table view and center it on the corresponding cell.

For a better user experience and more natural results, here I set the original cell background to black and add a fade to Snapshot view, making snapshot view a little larger than the original cell, aligning its y-coordinate offset to the y-axis of the gesture's position. When this is done, the cell jumps out of the table view, floats on top, and snaps to the user's finger.

12345678910111213141516171819202122232425262728293031323334 static UIView       *snapshot = nil;        ///< A snapshot of the row user is moving.static NSIndexPath  *sourceIndexPath = nil; ///< Initial index path, where gesture begins. switch (state) {  case UIGestureRecognizerStateBegan: {    if (indexPath) {      sourceIndexPath = indexPath;      UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];      // Take a snapshot of the selected row using helper method.      snapshot = [self customSnapshotFromView:cell];      // Add the snapshot as subview, centered at cell‘s center...      __block CGPoint center = cell.center;      snapshot.center = center;      snapshot.alpha = 0.0;      [self.tableView addSubview:snapshot];      [UIView animateWithDuration:0.25 animations:^{        // Offset for gesture location.        center.y = location.y;        snapshot.center = center;        snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);        snapshot.alpha = 0.98;        // Black out.        cell.backgroundColor = [UIColor blackColor];      } completion:nil];    }    break;  }  // More coming soon...}

Add the following method to the tail of the. m file. This method returns a corresponding snapshot view based on the view that was passed in.

1234567891011 -(UIView *) Customsnapshotfromview: (UIView *) Inputview {  &NBSP;&NBSP; uiview *snapshot = [Inputview Snapshotviewafterscreenupdates:yes]; &NBSP;&NBSP; snapshot.layer.maskstobounds = NO; &NBSP;&NBSP; snapshot.layer.cornerradius = 0.0; &NBSP;&NBSP; snapshot.layer.shadowoffset = Cgsizemake ( -5.0, 0.0); &NBSP;&NBSP; snapshot.layer.shadowradius = 5.0; &NBSP;&NBSP; snapshot.layer.shadowopacity = 0.4;  &NBSP;&NBSP; return snapshot;

When the gesture moves, that is, the UIGestureRecognizerStateChanged branch, you need to move the snapshot view (just set its Y-axis offset). If the distance from the gesture moves to another index path, you need to tell the table view to move the rows. At the same time, you need to update the data source:

1234567891011121314151617181920 case UIGestureRecognizerStateChanged: {  CGPoint center = snapshot.center;  center.y = location.y;  snapshot.center = center;  // Is destination valid and is it different from source?  if (indexPath && ![indexPath isEqual:sourceIndexPath]) {    // ... update data source.    [self.objects exchangeObjectAtIndex:indexPath.row withObjectAtIndex:sourceIndexPath.row];    // ... move the rows.    [self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];    // ... and update source so it is in sync with UI changes.    sourceIndexPath = indexPath;  }  break;}// More coming soon...

Finally, both table view and data source are up-to-date when the gesture ends or is canceled. All you need to do is remove the snapshot view from the table view and restore the cell's background color to white.

To improve the user experience, we'll fade the snapshot view and make it smaller to the same size as the cell. It looks like you put the cell back in place.

123456789101112131415161718192021 default: {  // Clean up.  UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:sourceIndexPath];  [UIView animateWithDuration:0.25 animations:^{    snapshot.center = cell.center;    snapshot.transform = CGAffineTransformIdentity;    snapshot.alpha = 0.0;    // Undo the black-out effect we did.    cell.backgroundColor = [UIColor whiteColor];  } completion:^(BOOL finished) {    [snapshot removeFromSuperview];    snapshot = nil;  }];  sourceIndexPath = nil;  break;}

That's it, it's done! Compile and run the program and you can now reorder tableview cells by long-press gestures!

You can download the complete sample project on GitHub.

How to use it on Uicollectionview?

Assuming you already have an example project in use UICollectionView , you can simply use the code described earlier in this article. All you need to do is self.collectionView replace it self.tableView and update the fetch and move UICollectionViewCell call methods.

Here's an exercise to checkout out Uicollectionview's starter project from GitHub, and then add tap-and-hold gestures to rearrange cells. This can be downloaded to a project that has been implemented well.

Go?

We deeply hope that you like this article! If you want to see an article like more Cookbook-style later, you can tell us.

In addition, if you would like to watch the video version of this article, you can come here to see.

In addition, I am happy to hear your comments and questions!

UITableView Long Press gesture

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.