UICollectionView 及 UICollectionViewCell 复用

来源:互联网 发布:潭州教育java 编辑:程序博客网 时间:2024/06/06 05:17

1、创建:

UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayoutalloc]init];

    flowLayout.scrollDirection =UICollectionViewScrollDirectionVertical;

    flowLayout.sectionInset =UIEdgeInsetsZero;

    flowLayout.minimumInteritemSpacing =0;

    flowLayout.minimumLineSpacing =5;

    

    _collectionView =[[UICollectionViewalloc]initWithFrame:CGRectMake(0,0,self.view.width, [UIScreenmainScreen].bounds.size.height-65)collectionViewLayout:flowLayout];


2、cell复用:

[_collectionViewregisterClass:[ImagePickCollectionViewCellclass]forCellWithReuseIdentifier:cellId];


ImagePickCollectionViewCell *cell = [_collectionViewdequeueReusableCellWithReuseIdentifier:cellIdforIndexPath:indexPath];


3、代理:

#pragma mark ---- UICollectionViewDataSource


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return1;

}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return_photos.count;

}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    ImagePickCollectionViewCell *cell = [_collectionViewdequeueReusableCellWithReuseIdentifier:cellIdforIndexPath:indexPath];

    cell.backgroundColor = [UIColorpurpleColor];

    

    //ALAsset *asset = _photos[indexPath.row];

    cell.imageView.image =_photos[indexPath.row];

    

    return cell;

}



#pragma mark ---- UICollectionViewDelegateFlowLayout


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

    float wid =CGRectGetWidth(_collectionView.bounds);

    returnCGSizeMake((wid -2*5)/3, (wid -2*5)/3);

}


4、注意:

cell 的 frame 不是以(0, 0)开头,添加子View时要注意,否则出现布局错乱。

0 0