使用UICollectionView进行圆形布局

因为前面已经对UICollectionView以及UICollectionViewlayout做过详细解说,所以就不再说明了,而是直接贴出UICollectionViewLayout的里面的代码!

#import "CircleLayout.h"

@interface CircleLayout()

@property (nonatomic,assign) NSInteger cellCount;

@property (nonatomic,assign) CGPoint center;

@property (nonatomic,assign) CGFloat radius;

@end


@implementation CircleLayout

#pragma mark - 实现内部的方法

// 设置contentSize每次滚动都会调用

- (CGSize)collectionViewContentSize

{

    return [selfcollectionView].frame.size;

}


// 设置初始化的东西该方法在每次刷新的时候都会调用,滚动时不会调用

- (void)prepareLayout

{

    [superprepareLayout];

    

    CGSize size =self.collectionView.frame.size;

    _cellCount = [[selfcollectionView] numberOfItemsInSection:0];

    // 大圆圆心位置

    _center =CGPointMake(size.width /2.0, size.height /2.0);

    // 大圆半径

    _radius =MIN(size.width, size.height) /4;

}


// 设置所有元素(比如cell、补充控件、装饰控件)的布局属性每次滚动都会调用

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

{

    NSMutableArray* attributes = [NSMutableArrayarray];

    for (NSInteger i=0 ; i <self.cellCount; i++) {

        //这里利用了-layoutAttributesForItemAtIndexPath:来获取attributes

        NSIndexPath* indexPath = [NSIndexPathindexPathForItem:i inSection:0];

        [attributes addObject:[selflayoutAttributesForItemAtIndexPath:indexPath]];

    }

    return attributes;

}


// 说明indexPath对应每一个cell的布局属性该方法在每次刷新的时候都会调用,滚动时不会调用

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath

{

    UICollectionViewLayoutAttributes* attributes = [UICollectionViewLayoutAttributeslayoutAttributesForCellWithIndexPath:indexPath];//生成空白的attributes对象,其中只记录了类型是cell以及对应的位置是indexPath

    //配置attributes到圆周上

    // 小圆大小和位置

    attributes.size =CGSizeMake(100,100);

    attributes.center =CGPointMake(_center.x +_radius * cosf(2 * indexPath.item * M_PI / _cellCount),_center.y +_radius * sinf(2 * indexPath.item * M_PI / _cellCount));

    return attributes;

}


@end



猜你喜欢

转载自blog.csdn.net/pbz106/article/details/53837369