GithubHelp home page GithubHelp logo

henrytkirk / htkdraganddropcollectionviewlayout Goto Github PK

View Code? Open in Web Editor NEW
169.0 11.0 41.0 46 KB

UICollectionViewLayout subclass that works together with a custom UICollectionViewCell to provide drag and drop for a UICollectionView. Works just like UITableView drag and drop. What's unique about this approach is that it does not need to create a "ghost" or "dummy" cell to provide the drag and drop functionality.

License: Apache License 2.0

Objective-C 94.99% Ruby 2.70% C 2.31%

htkdraganddropcollectionviewlayout's Introduction

HTKDragAndDropCollectionViewLayout

Custom UICollectionViewLayout that works together with a custom UICollectionViewCell to provide drag and drop for a UICollectionView. Works just like UITableView drag and drop. What's unique about this approach is that it does not need to create a "ghost" or "dummy" cell to provide the drag and drop functionality. I believe this method is simpler and less complex for the majority of use cases.

Adding to your project:

Cocoapods

CocoaPods is the recommended way to add HTKDragAndDropCollectionViewLayout to your project.

  1. Add a pod entry for HTKDragAndDropCollectionViewLayout to your Podfile pod 'HTKDragAndDropCollectionViewLayout'
  2. Install the pod(s) by running pod install.
  3. Subclass HTKDragAndDropCollectionViewController.
  4. Setup HTKDragAndDropCollectionViewLayout properties (itemSize, lineSpacing, etc).
  5. Subclass and use HTKDraggableCollectionViewCell which implements the gestures for dragging.
  6. Implement - (void)userDidEndDraggingCell:(UICollectionViewCell *)cell and if the HTKDragAndDropCollectionViewLayout finalIndexPath is not nil, insert the draggedIndexPath into the finalIndexPath's position. See example in project.

Sample video:

YouTube Sample Video

Screen shot:

Sample Screenshot

Change log:

v0.0.1: Initial project commit v0.1.0 - v0.1.2: Bug fixes - Don't use this version, I broke it. v0.1.3: Current stable version. This version is greatly enhanced over the original version. It now supports rotation, and inserting of items. Currently inserting only works to the "end" of the data source. So, if you have 10 items in your collectionView and wish to insert, adding the item to indexPath 0,10 will work fine, while adding to indexPath 0,5 would not. This should be corrected pretty soon.

Questions? Email: [email protected] or Web: http://www.henrytkirk.info

htkdraganddropcollectionviewlayout's People

Contributors

henrytkirk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

htkdraganddropcollectionviewlayout's Issues

IndexPath not exchanged when cells exchanged

I found when the the pan gesture is end, the delegate's userDidEndDraggingCell: will be called, and the resetDragging method too, but it doesn't exchange itemDictionary(the layout property) buckets.
I think it's a bug. when i want to exchange my datasource in userDidEndDraggingCell: callback method, the indexPath can't mapped to my datasource index correctly.

demo not working

Thank you for amazing component but no drag and drop functionality working...

userDidEndDraggingCell - update datasource not working

Sample application have a bug

  • (void)userDidEndDraggingCell:(UICollectionViewCell *)cell {
    [super userDidEndDraggingCell:cell];

    HTKDragAndDropCollectionViewLayout *flowLayout = (HTKDragAndDropCollectionViewLayout *)self.collectionView.collectionViewLayout;
    NSLog(@"%s %@",PRETTY_FUNCTION, self.collectionView.collectionViewLayout);//self.collectionView.collectionViewLayout = NIL!!!!
    // Save our dragging changes if needed
    if (flowLayout.finalIndexPath != nil) {
    // Update datasource
    NSObject *objectToMove = [self.dataArray objectAtIndex:flowLayout.draggedIndexPath.row];
    [self.dataArray removeObjectAtIndex:flowLayout.draggedIndexPath.row];
    [self.dataArray insertObject:objectToMove atIndex:flowLayout.finalIndexPath.row];
    }
    }

LOG:
start drag first item
-[HTKDragAndDropCollectionViewLayout prepareLayout] set finalIndexPath = nil and draggedIndexPath = nil
dragging over item
-[HTKDragAndDropCollectionViewLayout insertDraggedItemAtIndexPath:] set OK finalIndexPath.row = 0
release touch
-[HTKDragAndDropCollectionViewLayout prepareLayout] set finalIndexPath = nil and draggedIndexPath = nil
-[HTKDragAndDropCollectionViewLayout resetDragging] set finalIndexPath = nil and draggedIndexPath = nil
-[HTKSampleCollectionViewController userDidEndDraggingCell:]
We never go in to if for updating datasource

Incorrect spacing between cells

You need to change line 250 in HTKDragAndDropCollectionViewLayout.m to return actualItemSpacing / (self.numberOfItemsPerRow - 1);

Because you have only two spaces between three cells, you need to subtract one to space them evenly.

Dealing with bounds size change (e.g. interface orientation change)

with such setup

HTKDragAndDropCollectionViewLayout *flowLayout = (HTKDragAndDropCollectionViewLayout *)self.collectionView.collectionViewLayout;
    CGFloat itemWidth = CGRectGetWidth(self.collectionView.bounds) / 3;
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.lineSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

after performing interface rotation and thus changing collectionView width from 320 to 568 i expect items to "reflow" and form less rows with 5 items in a row instead of 3.
Is it possible to achieve it manually with the existing API?
Should it be done automatically?

i make it more flexible...

hi, i test this layout code today, and i found the selected cell need move very near to the target cell for exchanging position, so i modify two method to making it more flexible(marked with // ---->), can you check it out?

- (void)exchangeItemsIfNeeded {
    // Exchange objects if we're touching.
    NSIndexPath *intersectPath = [self indexPathBelowDraggedItemAtPoint:self.draggedCellCenter];
    UICollectionViewLayoutAttributes *attributes = self.itemDictionary[intersectPath];
    if (!attributes) return;  // add it for skip attributes == nil

    // ---->use attributes.frame not centerBox
    // Create a "hit area" that's 20 pt over the center of the intersected cell center
//    CGRect centerBox = CGRectMake(attributes.center.x - HTKDragAndDropCenterTriggerOffset, attributes.center.y - HTKDragAndDropCenterTriggerOffset, HTKDragAndDropCenterTriggerOffset * 5, HTKDragAndDropCenterTriggerOffset * 5);  

    // Determine if we need to move items around
    if (intersectPath != nil && ![intersectPath isEqual:self.draggedIndexPath] && CGRectContainsPoint(attributes.frame, self.draggedCellCenter)) {
        [self insertDraggedItemAtIndexPath:intersectPath];
    }
}

- (NSIndexPath *)indexPathBelowDraggedItemAtPoint:(CGPoint)point {

    __block NSIndexPath *indexPathBelow = nil;
    __weak HTKDragAndDropCollectionViewLayout *weakSelf = self;

    [self.collectionView.indexPathsForVisibleItems enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSIndexPath *indexPath = (NSIndexPath *)obj;

        // Skip our dragged cell
        if ([self.draggedIndexPath isEqual:indexPath]) {
            return;
        }
        UICollectionViewLayoutAttributes *attribute = weakSelf.itemDictionary[indexPath];

        // ---->use attributes.frame not centerBox
        // Create a "hit area" that's 20 pt over the center of the testing cell
//        CGRect centerBox = CGRectMake(attribute.center.x - HTKDragAndDropCenterTriggerOffset, attribute.center.y - HTKDragAndDropCenterTriggerOffset, attribute.frame.size.width/2, attribute.frame.size.height/2); 
        if (CGRectContainsPoint(attribute.frame, weakSelf.draggedCellCenter)) {
            indexPathBelow = indexPath;
            *stop = YES;
        }
    }];

    return indexPathBelow;
}

Incorrect final index when dragging cell to it's original position

Hi, when you drag a cell somewhere and then decide to drag it back (not move it), meaning you'll drop the cell at the spot where you started dragging it in one go, the finalindex will point to the last nearest position instead of on the original one.

To reveal this bug in your demo project reload collectionView data in userDidEndDraggingCell. The data underlying the collectionView isn't being changed properly.

scrollDirection

How to set scrolldirection horizontal. There is no property defined in HTKDragAndDropCollectionViewLayout to set scroll direction.

Bugs when items.count%2 == 1

when the items.count %2==1, the collectionView will appear with an error,the last row of the items will not be show.
Solve method:
In file HTKDragAndDropCollectionViewLayout.m,Method: - (CGSize)collectionViewContentSize add codes:

if (totalItems%2 == 1) {
totalItems=totalItems+1;
}

Final Codes:

- (CGSize)collectionViewContentSize {
CGFloat collectionViewWidth = CGRectGetWidth(self.collectionView.bounds);
// Determine number of sections
NSInteger totalItems = 0;
for (NSInteger i = 0; i < [self.collectionView numberOfSections]; i++) {
totalItems += [self.collectionView numberOfItemsInSection:i];
}
//When the totalItems%2 == 1,do this.
if (totalItems%2 == 1) {
totalItems=totalItems+1;
}
// Determine how many rows we will have

NSInteger rows = totalItems / self.numberOfItemsPerRow;

 // Determine height of collectionView

CGFloat height = (rows * (self.itemSize.height + self.lineSpacing)) + self.sectionInset.top + self.sectionInset.bottom;

`return CGSizeMake(collectionViewWidth, height);`

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.