objective-c - How to implement multiple layouts in a collectionview?
漂亮男人
漂亮男人 2017-05-02 09:29:10
0
0
705

The home page has been revised. The styles are as shown in Figures 1 and 2. Since 1 will have an extra line, I developed it myself according to ios - a method to solve the problem that the cell spacing of UICollectionView does not match the settings. I rewrote a class that inherits UICollectionViewFlowLayout LCHomeFlowLayout, its .m file is implemented as follows:

#import "LCHomeFlowLayout.h"

@implementation LCHomeFlowLayout

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    
    //从第二个循环到最后一个
    for(int i = 1; i < [attributes count]; ++i) {
        //当前attributes
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        //上一个attributes
        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        //我们想设置的最大间距,可根据需要改
        NSInteger maximumSpacing = 0;
        //前一个cell的最右边
        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
        //如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中,我们改变当前cell的原点位置
        //不加这个判断的后果是,UICollectionView只显示一行,原因是下面所有cell的x值都被加到第一行最后一个元素的后面了
        if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }
    return attributes;
}

@end

After running like this, the spacing between items in 2 is no longer there, but I set it to 10. How can I achieve this?
My collection view is initialized as follows:

 UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
//    LCHomeFlowLayout *flow = [[LCHomeFlowLayout alloc]init];
 _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 50) collectionViewLayout:flow];

Although the collection view has the @property (nonatomic, strong) UICollectionViewLayout *collectionViewLayout; attribute, how to call it?

漂亮男人
漂亮男人

reply all(0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template