Subclassing UICollectionViewFlowLayout sometimes c

2019-07-27 14:39发布

I want a UICollectionView where the flowlayout direction is horizontal. I've implemented the method targetContentOffsetForProposedContentOffset:withScrollingVelocity: to always "snap" the view to a cell in the collection view when scrolling in the table.

I have subclassed UICollectionViewFlowLayout like this (With the code for my implemented method from here: targetContentOffsetForProposedContentOffset:withScrollingVelocity without subclassing UICollectionViewFlowLayout)

@implementation SnappingFlowLayout

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [self customInit];
    }
    return self;
}

-(void)customInit
{
//    self.itemSize = CGSizeMake(75.0, 75.0);
    self.minimumInteritemSpacing = 0;
    self.minimumLineSpacing = 0;
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    CGFloat offsetAdjustment = MAXFLOAT;
    CGFloat horizontalOffset = proposedContentOffset.x;

    CGRect targetRect = CGRectMake(proposedContentOffset.x, 0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);

    NSArray *array = [super layoutAttributesForElementsInRect:targetRect];

    for (UICollectionViewLayoutAttributes *layoutAttributes in array) {
        CGFloat itemOffset = layoutAttributes.frame.origin.x;
        if (ABS(itemOffset - horizontalOffset) < ABS(offsetAdjustment)) {
            offsetAdjustment = itemOffset - horizontalOffset;
        }
    }
    int x = (proposedContentOffset.x + offsetAdjustment) >= 0 ? (proposedContentOffset.x + offsetAdjustment) : 0;
    return CGPointMake(x, proposedContentOffset.y);
}

When using this as a custom layout for my UICollectionView i sometimes get the following error when calling methods on the collection view, but ONLY on iOS6:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICollectionViewUpdateItem action]: unrecognized selector sent to instance

These methods are the ones that sometimes result in the error:

[self.collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionRight animated:YES];

and

[self.collectionView deleteItemsAtIndexPaths:indexPaths];

There is NOTHING wrong with my indexPaths. They work just fine on iOS7, and most of the time in iOS6 aswell.

Is there something obvious I've missed in my subclass implementation that is causing this?

Thank you.

0条回答
登录 后发表回答