具有动态大小单元间距问题的UICollectionViewCell

时间:2018-06-06 13:09:59

标签: ios objective-c uicollectionview uicollectionviewcell

我正在创建自定义UICollectionViewCell它的大小是从它的内容自动设置的。

单元格的动态大小正在工作,但它有额外的空间。

所以我想删除两个单元格之间的额外空间

我也设置了UICollectionView数据源和代理和Impalement它的方法但仍然无法正常工作

enter image description here

在One Row中没有修复他们唯一的2个单元格。它有1个,2个或3个单元格,它取决于文本

CustomeCollectionViewCell.m

- (CGSize)intrinsicContentSize
{
    CGSize size = self.lblText.intrinsicContentSize;
    size.width += 48;   // add padding Width that Given in Cell
    size.height += 32;  // add padding Height
    return size;
}

ViewController.m

@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) CustomeCollectionViewCell *tempCell;
@property (strong, nonatomic) NSArray *dataArr;
@end


- (void)viewDidLoad {
    [super viewDidLoad];

    self.dataArr = @[@"abcdef”,@"abcdef”,@"abcdef”,@"abcdef”,@"abcdef”];
    self.tempCell = (CustomeCollectionViewCell*) [[[UINib nibWithNibName:@“CustomeCollectionViewCell" bundle:nil] instantiateWithOwner:self options:nil] firstObject];

    [self.collectionView setContentInset:UIEdgeInsetsMake(8, 8, 8, 8)];
    [self.collectionView registerNib:[UINib nibWithNibName:@"CustomeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CustomeCollectionViewCell"];
}

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CustomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomeCollectionViewCell" forIndexPath:indexPath];
    cell.lblText.text = [self.dataArr objectAtIndex:indexPath.item];
    cell.backgroundColor = [UIColor blackColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    self.tempCell.lblText.text = [self.dataArr objectAtIndex:indexPath.item];
    return self.tempCell.intrinsicContentSize;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 8;
}

1 个答案:

答案 0 :(得分:0)

尝试使用以下委托方法

添加单元格的动态大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

    return CGSizeMake((self.view.frame.size.width - 15)/2, (self.view.frame.size.width - 15)/2);
}