IOS实现自定义布局瀑布流

2020-01-14 18:52:33刘景俊

注册cell


/**设置重用表示*/
static NSString *const ID = @"photo";
- (void)viewDidLoad
{
  [super viewDidLoad];

  [self setupCollectionView];

  //注册cell
  [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LYPPhotoCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
}

设置元素的个数


- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
  return self.imageNames.count;
}

设置每个元素的属性


- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
  //根据重用标示从缓存池中取出cell,若缓存池中没有,则自动创建
  LYPPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
  //设置cell的imageName属性
  cell.imageName = self.imageNames[indexPath.item];

  //返回cell
  return cell;
}

实现UICollectionView的代理方法,实现点击某个元素将其删除功能


- (void)collectionView:(nonnull UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
  //将图片名从数组中移除
  [self.imageNames removeObjectAtIndex:indexPath.item];
  //删除collectionView中的indexPath位置的元素
  [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
}

监听控制器view的点击,更换布局


- (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
  //判断当前布局的种类
  if ([self.collectionView.collectionViewLayout isKindOfClass:[LYPLineLayout class]])
  {
    //流水布局,切换至圆形布局
    [self.collectionView setCollectionViewLayout:[[LYPCircleLayout alloc] init] animated:YES];
  } else
  {
    //圆形布局,切换至流水布局
    LYPLineLayout *layout = [[LYPLineLayout alloc] init];
    //设置元素的尺寸,若不设置,将使用自动计算尺寸
    layout.itemSize = CGSizeMake(130, 130);
    [self.collectionView setCollectionViewLayout:layout animated:YES]; 
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助。



注:相关教程知识阅读请移步到IOS开发频道。