Giter Site home page Giter Site logo

lxcid / lxreorderablecollectionviewflowlayout Goto Github PK

View Code? Open in Web Editor NEW
1.9K 76.0 327.0 222 KB

Extends `UICollectionViewFlowLayout` to support reordering of cells. Similar to long press and pan on books in iBook.

Home Page: http://lxcid.com/

License: MIT License

Objective-C 97.86% Ruby 2.14%
uicollectionview reordering ibooks objective-c drag-and-drop uicollectionviewlayout

lxreorderablecollectionviewflowlayout's Introduction

LXReorderableCollectionViewFlowLayout

Extends UICollectionViewFlowLayout to support reordering of cells. Similar to long press and pan on books in iBook.

Features

The goal of LXReorderableCollectionViewFlowLayout is to provides capability for reordering of cell, similar to iBook.

  • Long press on cell to invoke reordering capability.
  • When reordering capability is invoked, fade the selected cell from highlighted to normal state.
  • Drag around the selected cell to move it to the desired location, the other cells adjust accordingly. Callback in the form of delegate methods are invoked.
  • Drag selected cell to the edges, depending on scroll direction, scroll in the desired direction.
  • Release to stop reordering.

Getting Started

Screenshot

  1. Install using CocoaPods or drag the LXReorderableCollectionViewFlowLayout folder into your project.

  2. Initialize/Setup your collection view to use LXReorderableCollectionViewFlowLayout.

  3. The collection view controller that is to support reordering capability must conforms to LXReorderableCollectionViewDataSource protocol. For example,

    - (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath willMoveToIndexPath:(NSIndexPath *)toIndexPath {
        id object = [mutableArray objectAtIndex:fromIndexPath.item];
        [mutableArray removeObjectAtIndex:fromIndexPath.item];
        [mutableArray insertObject:object atIndex:toIndexPath.item];
    }
    
  4. You can listen to some dragging events through comforming to LXReorderableCollectionViewDelegateFlowLayout methods.

  5. Setup your collection view accordingly to your need, run and see it in action! :D

Changes

Feb 24 2013 (Luke Scott)

  • Removed setUpGestureRecognizersOnCollectionView
  • Removed layout from delegate methods (can be accessed from collectionView)
  • Renamed delegate methods and split between dataSource and delegate
  • Added dataSource and delegate examples to sample project

Feb 23 2013 (Luke Scott)

  • Refactored everything to be more readable / maintainable
  • Deprecated setUpGestureRecognizersOnCollectionView - no longer necessary

Requirements

  • ARC
  • iOS 6 and above preferred
  • Xcode 4.5 and above

Credits

Alternatives

License

LXReorderableCollectionViewFlowLayout is available under the MIT license.

lxreorderablecollectionviewflowlayout's People

Contributors

antimoron avatar cbess avatar charlietuna avatar ferhatozduran avatar fillito avatar jessecurry avatar lukescott avatar lxcid avatar mstobetskyi avatar raphaelschaad avatar sibljon avatar timfether avatar tonyarnold 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  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

lxreorderablecollectionviewflowlayout's Issues

MIT license underspecified

Hi Folks,

Great work on this project. My team is using it and it's been really reliable. Alas, in the README it is stated that this is covered by the MIT license. Can you update the README to specify which one? There are several out there with slightly different wordings and my legal team is well, a legal team and persnickety.

I believe this is the one you intended to use: http://opensource.org/licenses/MIT). Copy and pasting the text into the README would be awesome and allow us to use this component.

Here's the wikipedia quote on why simply stating "The MIT License" isn't enough:
Because MIT has used many licenses for software, "MIT License" is considered ambiguous by the Free Software Foundation. "MIT License" may refer to the "Expat License" (used for Expat)[2] or to the "X11 License" (also called "MIT/X Consortium License"; used for the X Window System by the MIT X Consortium).[3] The "MIT License" published on the official site of Open Source Initiative[4] is the same as the "Expat License".

Thanks!

--chris

Deselected after shifting around

My cell that I am currently shifting stays selected, but after I shifted it around and set it down, it automatically deselects. Why did this deselection happen?

This only happens on the one I set down. All others remains selected, if any.

Is there a way to track the cell's position while it is being dragged?

I've got a tableview (on the left) and a reorderable collectionview on the right.

What I'd like to be able to achieve is the ability to drag from the collection view into the table view. Or at least highlight the cell in the table view while a collection view cell is being dragged on to it.

-------------------------------------
| tablecell |                       |
|-----------|  |------| |------|    |
| tcell2    |  | coll | | coll |    |
|-----------|  | cell | | cell2|    |
| tcell3    |  |------| |------|    |
|-----------|                       |
|                                   |
|                                   |
-------------------------------------

So in the above diagram, I could drag collcell2 over tcell3, and tcell3 would highlight.

To do this it seems I would have to be able to track the coll cell's position (while it's being dragged), and then somehow convert the co-ords into the table views system, and then highlight the relevant cell under that co-ord.

As a first step, is there a way to track these co-ords? Or would there be a better way of doing this?

Delete animation screwed up

    [self.m_collectionView.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];

This deletes the cell with nice animation BUT the cells gets squeezed together. See last row in photo. All I did was delete the last cell.

screen shot 2014-07-31 at 6 26 17 pm

[collectionView cellForItemAtIndexPath:indexPath] cell animates at wrong location

I have a classic UICollectionView inside of a viewController that uses a LXReorderableCollectionViewFlowLayout for reordering. The reordering works great and the underlying arrays change accordingly so the cells all show up in the right locations, but I'm having an issue where a subview of the cells is supposed to animate after being selected on didSelectItemAtIndexPath, using NSLog I can tell that the selection is showing the right indexPath as being selected but a totally different cell then the one at the indexPath is animating with the following:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
//animate press

    NSLog(@"indexPath cell is %@", [UICollectionView indexPathForCell:cell]); // returns the correct indexPath
    [UIView animateWithDuration:0.1f delay:0.0f options:UIViewAnimationOptionCurveEaseIn animations:^{
        cell.BackgroundView.alpha = 1.0f; //animates the wrong cell (not at indexPath reported by NSLog above)
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2f delay:0.0f options:UIViewAnimationOptionCurveEaseIn animations:^{
            cell.BackgroundView.alpha = 0.0f;
        } completion:^(BOOL finished) {

        }];
    }];

Here is the code from where I set up the collectionView

LXReorderableCollectionViewFlowLayout *flowLayout = [[LXReorderableCollectionViewFlowLayout alloc] init];
JobStencilLegendsCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(15.0f, 190.0f, 300.0f, 300.0f) collectionViewLayout:flowLayout];
JobStencilLegendsCollection.delegate = self;
JobStencilLegendsCollection.dataSource = self;

I have not changed the code for LXReorderableCollectionViewFlowLayout at all. Any ideas how the inclusion of this layout could affect which cell animates?

Problems with Supplementary Views

Before I start: AWESOME code!!!! This has saved me SO SO SO much time.

Here is my problem:
I've implemented you code by integrating it with my existing UICollectionView object:
@Property (nonatomic, strong) IBOutlet UICollectionView *myCollectionView;

In my viewDidLoad method I added this code:
LXReorderableCollectionViewFlowLayout *layout = [[LXReorderableCollectionViewFlowLayout alloc] init];
[self.myCollectionView setCollectionViewLayout:layout];
[layout setUpGestureRecognizersOnCollectionView];

Everything is working great except for my section headers. I am trying to support multiple sections in my collection view. I have changed the delegate that allows for move to allow for moving the items between sections and it works great.

The problem is that the section headers themselves don't show up. I see a space there but no text/graphics/buttons etc... I've tracked it down to the fact that my method:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

isn't getting called. Do I need to do something special here? The section headers show up fine without integrating your code, but dissappear when I add the above code. I'm kinda of a newb and completely confused.

Is this a problem with your code or mine? (I'm SURE it's mine)

Thanks for any help.

Crash When Unloading The Controller

I have a side menu structure and am trying to use this on the collection views for each item. When i tap a menu item, it replaces the active view controller with a new instance of the collection view controller containing the reorder able layout.

however, it crashes immediately. Removing the KVO solves the crash (but obviously makes the library useless).

any ideas?

thanks

UIGestureStateCancelled not handled

If I am in the middle of a reorder on a collection and then for example press a button with my spare finger on a tool bar that pushes another uiviewcontroller, the layout is left in an indeterminate state. When you return to the original view with the collection it is a 'mess'.

I solved it by copying out the lines in uigesturerecognizerstateended into a method and then calling that from both the stateEnded and stateCancelled cases.

I'm not sure how to do pull requests or anything yet so hope this helps.

This bug was found courtesy of my three year old son pawing at the screen. I find small children are excellent UI testers.

cellForItemAtIndexPath returns nil on LXReorderableCollectionViewDelegateFlowLayout

Hi. I'm using your library through pods.

I have a problem. I have to catch the cell that is on dragging states.

In these delegates,

  • (void)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout willBeginDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
  • (void)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout didBeginDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
  • (void)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout willEndDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
  • (void)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout didEndDraggingItemAtIndexPath:(NSIndexPath *)indexPath;

[collectionView cellForItemAtIndexPath:indexPath] returns nil.

This problem occurs your sample demo projects too.
Please check this issues. Thanks.

-[LXReorderableCollectionViewFlowLayout handleApplicationWillResignActive:] crash

Crashlytics report:

Exception Type: EXC_BAD_ACCESS Code: KERN_INVALID_ADDRESS at 0x1965

LXReorderableCollectionViewFlowLayout.m line 489
-[LXReorderableCollectionViewFlowLayout handleApplicationWillResignActive:]

  • (void)handleApplicationWillResignActive:(NSNotification *)notification {
    self.panGestureRecognizer.enabled = NO; // Line 489
    self.panGestureRecognizer.enabled = YES;
    }

Retain Cycle

If i use the LXReorderableCollectionViewFlowLayout, there is a retain cycle in my app. If you integrate the UICollectionView with this FlowLayout in your app the ViewController is never dealloced by the system.

It seems there is a retain cycle in the LXReorderableCollectionViewFlowLayout if i switch my UICollectionView to UICollectionViewFlowLayout everything is fine…

proper method names and usage for layout

add optional method to LXReorderableCollectionViewDataSource

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath;

check if animation finished, perform moving in performBatchUpdates

    if ([self.dataSource respondsToSelector:@selector(collectionView:itemAtIndexPath:willMoveToIndexPath:)]) {
        [self.dataSource collectionView:self.collectionView itemAtIndexPath:previousIndexPath willMoveToIndexPath:newIndexPath];
    }

    __weak typeof(self)weakSelf = self;
    [self.collectionView performBatchUpdates:^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (strongSelf) {
            if ([strongSelf.dataSource respondsToSelector:@selector(collectionView:moveItemAtIndexPath:toIndexPath:)]) {
                [strongSelf.dataSource collectionView:strongSelf.collectionView moveItemAtIndexPath:previousIndexPath toIndexPath:newIndexPath];
            }

            [strongSelf.collectionView deleteItemsAtIndexPaths:@[ previousIndexPath ]];
            [strongSelf.collectionView insertItemsAtIndexPaths:@[ newIndexPath ]];
        }
    } completion:^(BOOL finished) {
        if (finished) {
                __strong typeof(weakSelf)strongSelf = weakSelf;
                if ([strongSelf.dataSource respondsToSelector:@selector(collectionView:itemAtIndexPath:didMoveToIndexPath:)]) {
                    [strongSelf.dataSource collectionView:strongSelf.collectionView itemAtIndexPath:previousIndexPath didMoveToIndexPath:newIndexPath];
                }
        }
    }];

Book Shelf view -Reorder the shelves(Sections)

First Thanks for the great post. I have created the book shelf view(similar to iBooks) using collection view.Now i am trying to swap/re-order the shelf just like tableview reordering of cells. i.e when I pick a shelf and reorder it, the shelf should move up and down. Is there any way to achieve this effort?. Please suggest me. Thank you in advance.

trying to add a zoom slider to the collection

hey everyone,

i love this reorderable flowlayout and i tried to use it in a project where im changing the cell sizes with a uislider.

everything works grate until the cells are reaching a size where they can fit only one per line.

then the following thing happens:
screen shot 2013-05-02 at 6 28 29 pm

does anyone have any idea why this happens ?

to enable zooming i added the following code to the sample demo with the cards:

in LXCollectionViewController.h file

@Property (strong, nonatomic) UISlider *zoomController;
@Property (nonatomic) CGFloat zoomLevel;

and in LXCollectionViewController.m file

-(IBAction)sliderValueChanged:(UISlider *)sender
{
self.zoomLevel = self.zoomController.value;
[self.collectionView reloadData];
[self.collectionView.collectionViewLayout invalidateLayout];
}

  • (CGSize)collectionView:(UICollectionView )collectionView layout:(UICollectionViewLayout)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {

    return CGSizeMake(160 + self.zoomLevel, 240 + self.zoomLevel);

}

-(void) addZoomController {
self.zoomController = [[UISlider alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50)];
[self.zoomController addTarget:self action:@selector(sliderValueChanged:)
forControlEvents:UIControlEventValueChanged];

self.zoomController.minimumValue = -400;
self.zoomController.maximumValue = 400;

self.zoomLevel = 0;
[self.view addSubview:self.zoomController];

}

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.deck = [self constructsDeck];

    [self addZoomController];
    }

Why not move instead of insert/delete?

Any reason for not using moveItemAtIndexPath:toIndexPath: instead of insert/delete here?

Move appears to be a little bit more efficient. Also, it would make the block unnecessary.

UICollectionViewController vs UICollectionView

I'm new to Obj-C and GitHub. But I've been trying to use this framework on a UICollectionView and not on a UICollectionViewController. My array is manually entered. I have the layout folder in my project and as far as I know it is hooked up correctly. The UICollectionView renders and scrolls but gestures are not recognized. I was wondering if I have to use cellForItemAtIndexPath in a similar manner as you did or is the layout code all that needs to be added?

-(UICollectionViewCell *)collectionView:(UICollectionView *)sortCollectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SortCellIndentifier = @"SortCell";
SortCell *cell = [sortCollectionView dequeueReusableCellWithReuseIdentifier:SortCellIndentifier forIndexPath:indexPath];
[[cell sortImage]setImage:[UIImage imageNamed:[self.sortArrayOfImages objectAtIndex:indexPath.item]]];
return cell;

}

-(void)collectionView:(UICollectionView *)sortCollectionView layout:(UICollectionViewLayout *)theLayout itemAtIndexPath:(NSIndexPath *)indexPath willMoveToIndexPath:(NSIndexPath *)theToIndexPath {
id theFromItem = [self.sortArrayOfImages objectAtIndex:indexPath.item];
[self.sortArrayOfImages removeObjectAtIndex:indexPath.item];
[self.sortArrayOfImages insertObject:theFromItem atIndex:indexPath.item];
}

EXC_BAD_ACCESS when popping the UICollectionView from UINavigationController's stack

Hey!

You did a really great job on this one! Thank you for sharing it with us :)

I'm experiencing an issue since I updated to the latest version of LXReorderableCollectionViewFlowLayout:

When I remove a UICollection view from the navigation stack of UINavigationController my app crashs with EXC_BAD_ACCESS. I inserted log statements in the layouts methods to see which one is called las, it is invalidateScrollTimer. I actived NSZombies to see where the errors happens, it seems related to some instance of NSSet / CFSet. Please have a look at my screenshot of the debugger for more information:

https://www.evernote.com/shard/s3/sh/27eaeb40-5d48-455f-b483-e3e8caa54bba/3a1837282deb1dc374be7a3d14ab1aa7/deep/0/Screen%20Shot%202013-05-02%20at%2015.58.33.png

Is this an issue related to my implementation or a bug in the layout? Any help is appreciated.

Best regards,

Chris

Is it necessary to be a subclass?

What makes it necessary for this logic to be a subclass of UICollectionViewFlowLayout? Can't we apply the Decorator design pattern to a UICollectionView?

I ask because I have my own UICollectionViewFlowLayout subclasses, and this forces me to make changes to the LXReorderableCollectionViewFlowLayout code.

EXC_BAD_ACCESS when layout is changed on collection view

Steps to simulate:

  1. Set collection view the LXReoderableCollectionViewFlowLayout
  2. After the collection view is visible on screen change the layout using [UICollectionView setCollectionViewLayout:<new layout instance. (Any layout class will work.)
  3. Perform any gesture on the collection view. (long press or swipe will work)
  4. EXC_BAD_ACCESS

Problem with customizing cell size

In the demo project, add the following code to LXCollectionViewController.m

  • (CGSize)collectionView:(UICollectionView )collectionView layout:(UICollectionViewLayout)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    return CGSizeMake(indexPath.row == 0 ? 200 : 100, 100);
    }

The resulted screen is like this. The last row is messed up:

ios simulator screen shot may 22 2014 3 48 15 pm

Drag to empty section not supported

Hi,
this great layout is easily extended to support multiple sections and section headers (with supplementary views). Drag and drag between sections works out-of-the-box. However dragging to empty sections is not supported, because drop targets are apparently only the items themselves.
Has anyone a clue how to solve this problem? Thank you so much!

Renames project to LXCollectionViewSortableFlowLayout

Slightly shorter name and more correct way of naming. Apple seems to follow the following convention:

[Prefix] + CollectionView + [Layout Characteristic] + Layout

Example: UICollectionViewFlowLayout

Would like to gather feedback on this.

Items don't shift while scrolling

While reordering, the collection view will automatically scroll when you hit an edge, but the items don't reorder as that scroll occurs.

Animation glitches when reordering cells of different size

Hi, i've been using your layout for a while and encountered following problem:
Basically, I mimic table view via UICollectionView (cell width = screen width, no gaps between cells) to be able to reorder my cells -> but I need to display reordering control in a different location inside my custom cell, but, alas, UITableViewCell do not allow me to do this without some trickery.

I forked your repo here - selasie@a9dd083

And fixed following issue (although it might be specific to my project only, but it might help someone, someday):

When I reorder cells of different height (especially, when you drag cell with lesser height above cell with bigger height) there is a lot of glitches with inserting / deleting cells animation.
I restricted movement only to Y-axis (in handlePanRecoginzer: I use only y component of translation point), and modified invalidateLayoutIfNecessary method to handle following condition:
If we moving same direction (for now, I check only for vertical movement up and down) and trying to swap cells with index path similar to previously swapped cells (e.g. we swapped cells at indexes 0 and 1, and now trying to swap cell at index 1 with cell at index 0) - we assume that this scenario is wrong and do nothing, otherwise - continue swapping.

Any thoughts on how to integrate this in XIBs?

Has anyone had success integrating this using XIBs? If so, can you post an example?

I feel like I'm getting close, I'm getting the app to crash on long press: [UICollectionReusableView setHighlighted:]: unrecognized selector sent to instance 0xac485c0

My setup:

FileListViewController.h

@interface FileListViewController : UICollectionViewController <UICollectionViewDataSource, UICollectionViewDelegate, LXReorderableCollectionViewDelegateFlowLayout>

FileListViewController.m

- (id)init {
    // UICollectionViewFlowLayout
    LXReorderableCollectionViewFlowLayout *flowLayout = [[LXReorderableCollectionViewFlowLayout alloc] init];
    [flowLayout setUpGestureRecognizersOnCollectionView];
    return [self initWithCollectionViewLayout:flowLayout];
}

Thanks!

Any way to prevent the last cell from being reordered?

I was able to prevent the last cell from allowing it self to be selected for reordering, but I would like to still be able to prevent other cells from reordering to its position. Essentially I want the last cell to be and "add item" and therefor always at the very end.

Any ideas?

0.1.1 not available through CocoaPods

I haven't really figured out how CocoaPods works yet, so I'm not sure what the problem is here.

If you search for LXReorderableCollectionViewFlowLayout on CocoaPods.org, the version listed is 0.1.0.beta1. If I try to use 0.1.1 in my Podfile, I get an error on pod install:

[!] Unable to satisfy the following requirements:
- `LXReorderableCollectionViewFlowLayout (~> 0.1.1)` required by `Podfile`

The version in the podspec was bumped to 0.1.1 in cc31519. Maybe this update just needs to be pushed to CocoaPods using pod push master?

Crash In Empty Collections

I found a crash in the handleLongPressGesture: method that occurs when one display an empty collection.

I don't have time to fork, fix, test, and send a pull request this week, but I was able to fix it by wrapping lines starting at 222 with "if ( theIndexPathOfSelectedItem )" to make sure that we don't have a nil indexPath before attempting to handle UIGestureRecognizerStateEnded.


    case UIGestureRecognizerStateEnded: {
        NSIndexPath *theIndexPathOfSelectedItem = self.selectedItemIndexPath;

        if ([self.collectionView.delegate conformsToProtocol:@protocol(LXReorderableCollectionViewDelegateFlowLayout)]) {
            id<LXReorderableCollectionViewDelegateFlowLayout> theDelegate = (id<LXReorderableCollectionViewDelegateFlowLayout>)self.collectionView.delegate;
            if ([theDelegate respondsToSelector:@selector(collectionView:layout:willEndReorderingAtIndexPath:)]) {
                [theDelegate collectionView:self.collectionView layout:self willEndReorderingAtIndexPath:theIndexPathOfSelectedItem];
            }
        }

        self.selectedItemIndexPath = nil;
        self.currentViewCenter = CGPointZero;

        if ( theIndexPathOfSelectedItem )
        {
            UICollectionViewLayoutAttributes *theLayoutAttributes = [self layoutAttributesForItemAtIndexPath:theIndexPathOfSelectedItem];

            __weak LXReorderableCollectionViewFlowLayout *theWeakSelf = self;
            [UIView
             animateWithDuration:0.3f
             animations:^{
                 __strong LXReorderableCollectionViewFlowLayout *theStrongSelf = theWeakSelf;

                 theStrongSelf.currentView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
                 theStrongSelf.currentView.center = theLayoutAttributes.center;
             }
             completion:^(BOOL finished) {
                 __strong LXReorderableCollectionViewFlowLayout *theStrongSelf = theWeakSelf;

                 [theStrongSelf.currentView removeFromSuperview];
                 [theStrongSelf invalidateLayout];

                 if ([self.collectionView.delegate conformsToProtocol:@protocol(LXReorderableCollectionViewDelegateFlowLayout)]) {
                     id<LXReorderableCollectionViewDelegateFlowLayout> theDelegate = (id<LXReorderableCollectionViewDelegateFlowLayout>)self.collectionView.delegate;
                     if ([theDelegate respondsToSelector:@selector(collectionView:layout:didEndReorderingAtIndexPath:)]) {
                         [theDelegate collectionView:self.collectionView layout:self didEndReorderingAtIndexPath:theIndexPathOfSelectedItem];
                     }
                 }
             }];
        }
    } break;

Limit reordering to within single section

I just found your project and it looks like it will potentially be a great fit for a new app that I'm working on!

I've just started to look at your code and was wondering what you think here. I'd like to limit reordering of items to be only in the same section as they are originally found with. Do you have any recommendations on how to achieve this?

Thanks much,
S

The reordering animations are not canceled when all the cells fit to screen

There is a problem with LXReorderableCollectionViewFlowLayout when all your cells fit to one screen and you do the following:

  • Use the simulator and turn on slow animations
  • Drag one cell (for example the 1st) to 2nd position and immediately when the cell reordering has begun drag the cell back to the 1st position
  • This will lead to a situation where the first cell reordering animation is not canceled and continues to move

However, if you increase the number of cells so, that they all don't fit to the screen - the previous animations are canceled.

You can replicate this behavior with the LXRCVFL Example using Storyboard by modifying LXCollectionViewController.m to supply only 6 cells (6 cards). Then start the example with the simulator, turn on slow animations and drag the first cell to second position and immediately back (and then again). You'll see that the old animations are not canceled. However, if you run the example with, say 52 cards, the behavior is gone.

It seems that, for some odd reason, [collectionView performBatchUpdates:] is not canceled in invalidateLayoutIfNecessary (LXReorderableCollectionViewFlowLayout line 97), when the cells fit to one screen.

Transparent Cells

I have an issue with a transparent cell, when I do a long press, and cell gets scaled up a little, the background of the cell becomes black, and it briefly flickers.

Content Insets and Merging Items

Awesome project going on here! Honestly it was SO useful.

I've extended it just a bit and I want to know if it's worth pushing up to github. Essentially, we wanted to merge photo thumbnails into groups, so I added a few delegate methods following the same type of architecture so it can tell if you're finger is over another cell - if you drop there a delegate method will trigger (collectionView:willmergeFromIndex:ToIndex:) of course checking that the original cell can be moved and that the destination cell is kosher for merging.

Was there any consideration of collection view content insets in the auto scrolling

App crashing with message sent to dealloc instance

When I dismiss my modal (storyboard) that has a LXReorderableCollectionViewFlowLayout I get this:

*** -[CFSet countByEnumeratingWithState:objects:count:]: message sent to deallocated instance 0xb7b66d0
Unfortunately, no stack trace is provided so I can't see the exact line it crashes on.

I tried setting up LXReorderableCollectionViewFlowLayout in code instead of in IB and got the same behavior.
When I remove the LXReorderableCollectionViewFlowLayout the modal dismisses fine.

Here is my code:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.assets = [[NSMutableArray alloc] init];
    photoUploadInfoArray = [[NSMutableArray alloc] init];
    LXReorderableCollectionViewFlowLayout *flowLayout = [[LXReorderableCollectionViewFlowLayout alloc] init];
    self.photoCollectionView.collectionViewLayout = flowLayout;
    flowLayout.itemSize = CGSizeMake(100, 100);
    flowLayout.minimumInteritemSpacing = 1;
    [self.photoCollectionView registerClass:[UpdateCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
}

Bug and Feature Request

Thank you for your codes, really save me a lot of time. Unfortunately, something wrong when I try to use it. I'm writing everything with codes so no storyboard stuff. Here's my problems:

Screen Shot 2013-01-05 at 12 09 40 AM

  • There's a custom viewcell I'm dragging in the picture. And there's a black backgroundColor which I don't need.
  • There's a 'plus' cell in the collection view. Which should not be draggable. When I look into your code, There's not such interface for these. So I think there should be an api which may look exactly like the UITableView's datasource api.

Thank you for your code.

drag-n-frop improvement

may be this will be better solution

    CGRect intersectionFrame = CGRectIntersection(self.currentView.frame, theFrame);
    if (intersectionFrame.size.height > theFrame.size.height/2 && intersectionFrame.size.width > theFrame.size.width/2) {
        [self dropCurrentItemOnIndexPath:newIndePath];
    } else {
        [self moveCurrentItemToIndexPath:newIndePath];
    }

Getting the new order of items after sort.

I've been trying to get the resulting order after the cells have been moved.

I've used this to make an array. I've noticed the index order seems to vary and of course I get an indexPath for visible cells.

NSArray *visible = [self.collectionView indexPathsForVisibleItems]; NSMutableArray *rowsArray = [NSMutableArray arrayWithCapacity:[visible count]]; [visible enumerateObjectsUsingBlock:^(NSIndexPath *indexPath, NSUInteger idx, BOOL *stop) { [rowsArray addObject:@(indexPath.item)];

    NSLog(@"This is the indexPathsForVisibleItems as array named visible %@", visible);`

But I want to peek inside and get new order. I wish I knew how to get the image displayed in a cell by using the indexPath for the visible cells after a sort but I'm not sure how to do that.

I can get the object at a cell using something like this.

NSObject *getCell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

I get the layout object.

cellForItemAtIndexPath: returns nil for reordered cell

I apply an animation to cells when they can be moved. Much like Apple does when reordering apps on the springboard.
The animation disappears after a cell has been moved. This is not a problem, I can just apply it again afterwards but it's not possible to grab the cell again as cellForItemAtIndexPath: will return null for the index path which the cell was moved to.

Example:

- (void)collectionView:(PSTCollectionView *)theCollectionView layout:(PSTCollectionViewLayout *)theLayout didEndReorderingAtIndexPath:(NSIndexPath *)theIndexPath
{
    PSTCollectionViewCell *cell = [theCollectionView cellForItemAtIndexPath:theIndexPath]; // is null
}

Assertion failure in [UICollectionView _endItemAnimations]

I get an error after incorporate LXReorderableCollectionViewFlowLayout in my application.

My aplication work well and drag and drop cell well, but when I try to drag first view in my collection view, application report:

013-04-16 18:24:35.049 PowerComicReader[5354:c07] will begin drag
2013-04-16 18:24:35.352 PowerComicReader[5354:c07] did begin drag
2013-04-16 18:24:35.881 PowerComicReader[5354:c07] *** Assertion failure in -[UICollectionView _endItemAnimations], /SourceCache/UIKit_Sim/UIKit-2380.17/UICollectionView.m:2801

Always broke in line:
[self.collectionView performBatchUpdates:^{

Of file: LXReorderableCollectionViewFlowLayout.m

Any idea about this problem?

Thanks

Thread 1: EXEC_BAD_ACCESS (code=1) when dismissing view controller with collection

Not sure why this is happening, I've implemented as follows:

LXReorderableCollectionViewFlowLayout *layout = [[LXReorderableCollectionViewFlowLayout alloc] init];
[collection setCollectionViewLayout:layout];

And collection is a UICollectionView inside a UIViewController that I manually segue to. The dragging and dropping and reordering works fine with the itemAtIndexPath:fromIndexPath willMoveToIndexPath:toIndexPath function.

However, as soon as I dismiss the view controller with:

[self dismissViewControllerAnimated:YES completion:nil];

I'm hit with the Thread 1: EXEC_BAD_ACCESS (code=1) error.

Any ideas what I could be doing wrong here? The view worked perfectly before I implemented this.

Thanks.

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.