如图所示效果,根据字符长度自适应UICollectionViewCell
的大小,同时进行左对齐处理。
如何实现
继承UICollectionViewFlowLayout
创建子类,并实现相关的方法,如:
1、- (void)prepareLayout;
2、- (CGSize)collectionViewContentSize;
3、- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;
具体怎么编码实现
代码示例如下:
1、UICollectionViewFlowLayout
子类
.h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol CollectionLayoutDelegate <NSObject>
/// 获取item高度
- (CGFloat)widthForItemIndexPath:(NSIndexPath *)indexPath AndCollectioinView:(UICollectionView *)collectionView;
@end
@interface CollectionLayout : UICollectionViewFlowLayout
@property (nonatomic, weak) id<CollectionLayoutDelegate>delegate;
/// 视图宽
@property (nonatomic, assign) CGFloat layoutWidth;
/// 自适应collection的大小(默认NO)
@property (nonatomic, assign) BOOL autoContentSize;
@end
.m文件
#import "CollectionLayout.h"
@interface CollectionLayout ()
// 临时保存item的总宽度
@property (nonatomic, assign) CGFloat columnWidth;
// 记录一共有多少行
@property (nonatomic, assign) NSInteger columnNumber;
// 保存每一个item x y w h
@property (nonatomic, retain) NSMutableArray *arrForItemAtrributes;
// 保存item总数
@property (nonatomic,assign) NSUInteger numberOfItems;
// 保存每个item的X值
@property (nonatomic, assign) CGFloat xForItemOrigin;
// 保存每个item的Y值
@property (nonatomic, assign) CGFloat yForItemOrigin;
@end
@implementation CollectionLayout
// 准备布局
- (void)prepareLayout
{
[super prepareLayout];
//
self.columnWidth = self.sectionInset.left;
self.columnNumber = 0;
self.arrForItemAtrributes = [NSMutableArray array];
self.xForItemOrigin = self.sectionInset.left;
self.yForItemOrigin = self.sectionInset.top;
// 获取item的个数
self.numberOfItems = [self.collectionView numberOfItemsInSection:0];
/** 为每个item确定LayoutAttribute属性,同时将这些属性放入布局数组中 */
for (int i = 0; i < self.numberOfItems; i++) {
/** 确定每个Item的indexPath属性 */
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
/** 确定每个item的origin的x,y值 */
/** 确定每个Item的frame属性,同时确定了每个Item的LayoutAttribute,放入到了布局属性数组中 */
[self setFrame:in