UICollectionview使用装饰decorationView

自定collectionview的装饰视图

先来看一下效果图

在这里插入图片描述
图中树的部分就是通过装饰来实现的;
要想实现图中树杈部分的UI,如果通过传统的方式很难实现,只能写死一部分UI来实现这样的效果,但是通过collectionview的decorationView就可以轻松的实现这种效果;
先上代码

步骤3:
[self registerClass:[ShelfView class] forDecorationViewOfKind:[ShelfView kind]];

步骤4:
- (void)prepareLayout {
 if (self.scrollDirection == UICollectionViewScrollDirectionVertical)
    {
        int sectionCount = (int)[self.collectionView numberOfSections];
        
        CGFloat y = 0;
        CGFloat availableWidth = self.collectionViewContentSize.width - (self.sectionInset.left + self.sectionInset.right);
        int itemsAcross = floorf((availableWidth + self.minimumInteritemSpacing) / (self.itemSize.width + self.minimumInteritemSpacing));
        for (int section = 0; section < sectionCount; section++)
        {
        if (section == 1) {
                self.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH * 0.7);
              }else {
                self.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 45);
              }
            
            y += self.headerReferenceSize.height;

            int itemCount = (int)[self.collectionView numberOfItemsInSection:section];
            int rows = ceilf(itemCount/(float)itemsAcross);
                dictionary[[NSIndexPath indexPathForItem:0 inSection:section]] = [NSValue valueWithCGRect:CGRectMake(0, y, self.collectionViewContentSize.width, 81)];
            y += self.sectionInset.top;
            y += self.sectionInset.bottom;
            y += (self.itemSize.height)*rows;
            y += self.minimumLineSpacing*rows;
        }
    }
        self.shelfRects = [NSDictionary dictionaryWithDictionary:dictionary];
}

步骤5:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

// Add our decoration views (shelves)
    NSMutableArray *newArray = [array mutableCopy];
    
    [self.shelfRects enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if (CGRectIntersectsRect([obj CGRectValue], rect))
        {
            
            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:[ShelfView kind] withIndexPath:key];
            attributes.frame = [obj CGRectValue];
            attributes.zIndex = 1;
            //attributes.alpha = 0.5; // screenshots
            [newArray addObject:attributes];
        }
    }];

    array = [NSArray arrayWithArray:newArray];
}

只需要以下几步就可以实现一个自定义装饰步骤:

1.自定义decorationViewMyDecorationView``继承UICollectionReusableView
2.自定义collectionviewlayout;
3.在layout初始化的时候注册MyDecorationView;
4.在layout中的prepare中计算装饰的frame;
5.在布局方法- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;方法中将计算的frame赋值给指定的decorationView;

发布了35 篇原创文章 · 获赞 9 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/SunFlowerInRain/article/details/102845789