自定义UICollectionViewFlowLayout具有水平分页/滚动的垂直布局

时间:2015-12-30 09:48:49

标签: ios objective-c uicollectionview uicollectionviewlayout

-----------------------------------
1 2 3 4 |  9 10 11 12 | 17 18 19 20
5 6 7 8 | 13 14 15 16 | 21 22 23 24
-----------------------------------
 Page 1      Page 2        Page 3

我目前有一个工作布局,但它在大屏幕(6加)上搞砸了。

屏幕截图:All other devices& iphone 6+

#import <UIKit/UIKit.h>

@interface TagCollectionLayout : UICollectionViewFlowLayout

@property (nonatomic) NSInteger nbColumns;
@property (nonatomic) NSInteger nbLines;

@end

#import "TagCollectionLayout.h"

@implementation TagCollectionLayout

- (instancetype)init{
    self = [super init];
    if(self){
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.nbColumns = -1;
        self.nbLines = -1;
    }
    return self;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger nbColumns = self.nbColumns != -1 ? self.nbColumns : (int)(self.collectionView.frame.size.width / self.itemSize.width);
    NSInteger nbLines = self.nbLines != -1 ? self.nbLines : (int)(self.collectionView.frame.size.height / self.itemSize.height);

    NSInteger idxPage = (int)indexPath.row/(nbColumns * nbLines);

    NSInteger O = indexPath.row - (idxPage * nbColumns * nbLines);

    NSInteger xD = (int)(O / nbColumns);
    NSInteger yD = O % nbColumns;

    NSInteger D = xD + (yD * nbLines) + (idxPage * nbColumns * nbLines);

    NSIndexPath *fakeIndexPath = [NSIndexPath indexPathForItem:D inSection:indexPath.section];

    return [super layoutAttributesForItemAtIndexPath:fakeIndexPath];
}

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
    CGFloat newX = MIN(0, rect.origin.x - rect.size.width/2);
    CGFloat newWidth = rect.size.width*2 + (rect.origin.x - newX);

    CGRect newRect = CGRectMake(newX, rect.origin.y, newWidth, rect.size.height);

    // Get all the attributes for the elements in the specified frame
    NSArray *allAttributesInRect = [super layoutAttributesForElementsInRect:newRect];

    for (UICollectionViewLayoutAttributes *attr in allAttributesInRect) {
        UICollectionViewLayoutAttributes *newAttr = [self layoutAttributesForItemAtIndexPath:attr.indexPath];
        attr.frame = newAttr.frame;
        attr.center = newAttr.center;
        attr.bounds = newAttr.bounds;
        attr.hidden = newAttr.hidden;
        attr.size = newAttr.size;
    }
    return allAttributesInRect;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}

@end

你们对于为什么大屏幕有这个奇怪的问题有什么想法吗?

0 个答案:

没有答案