1. 创建“WYWaterflowLayout”继承制 “UICollectionViewLayout”。
2. 在“ViewController” 中导入“WYWaterflowLayout”类。并创建,创建的代码如下
@property (nonatomic,weak) UICollectionView *collectionView;
- (void)CircleLayout { WYWaterflowLayout *layout = [[WYWaterflowLayout alloc] init]; // 创建CollectionView UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; collectionView.dataSource = self; collectionView.backgroundColor = [UIColor whiteColor]; [self.view addSubview:collectionView]; self.collectionView = collectionView; // 使用系统自带的类注册 // [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:WYShopID]; // 使用自定义类注册 [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([XMGShopCell class]) bundle:nil] forCellWithReuseIdentifier:WYShopID]; }
3. 数据源<UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { self.collectionView.footer.hidden = self.shops.count == 0; return self.shops.count; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { XMGShopCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:WYShopID forIndexPath:indexPath]; XMGShop *shopses = self.shops[indexPath.item]; cell.shop = shopses; return cell; }
4. 写 “WYWaterflowLayout”的方法,这四个类是必须要写的。
// 初始化 - (void)prepareLayout; // 决定cell的排布 - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect; // 返回indexPath位置cell对应的布局属性 - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath; - (CGSize)collectionViewContentSize
时间: 2024-10-22 16:36:47