UICollectionView与自行调整单元格无法正确计算contentSize

Grz*_*ski 7 objective-c ios uicollectionview uicollectionviewlayout

我在UICollection视图中使用自定义单元格,如WWDC 2014所示.

我想把它放在一个UITableViewCell中并显示一个标签云(我希望在Foursquare应用程序中实现的目标很好: http://i59.tinypic.com/sxd9qf.png)

我的问题是,对于自定义单元格,内容大小不正确返回.我准备了一些快速演示来显示问题:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.elements = [NSMutableArray array];
    for (int i = 0; i < 23; i++)
    {
        [self.elements addObject:[self randomString]];
    }

    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc] init];
    layout.estimatedItemSize = CGSizeMake(50, 30);

    self.collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    [self.collectionView setDataSource:self];
    [self.collectionView setDelegate:self];

    UINib *cellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"CustomCell"];
    [self.collectionView setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:self.collectionView];
}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    self.collectionView.frame = CGRectMake(0, 0, self.collectionView.frame.size.width, self.collectionView.contentSize.height);
}

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];
    cell.customLabel.text = [self.elements objectAtIndex:[indexPath row]];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

当我以旧方式执行并删除estimatedItemSize并使用itemSize或委托方法来计算大小 - 它正常工作,所以我认为它使用的是estimateItem大小来获取内容大小.

有没有办法让它适用于自定义单元格并自动调整UICollectionView的内容?

Grz*_*ski 1

我最终自己计算了尺寸:

- (CGSize) sizeForCellAtIndexPath:(NSIndexPath*) indexPath isMoreButton:(BOOL) isMoreButton
{
    TagCell* cell = (TagCell*) [[LayoutHelper sharedLayoutHelper] collectionCellFromNib:@"TagCell"];
    cell.tagLabel.text = [self.contactHashTags objectAtIndex:indexPath.row];
    CGSize size = [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    CGSizeMake(size.width, cell.frame.size.height);
}

- (CGSize) sizeForCellAtIndexPath:(NSIndexPath*) indexPath isMoreButton:(BOOL) isMoreButton
{
    CGSize size = [self.dataSource sizeForCellAtIndexPath:indexPath isMoreButton:isMoreButton];

    //limit cell to view width
    size.width = MIN(size.width, self.frame.size.width);
    return size;
}
Run Code Online (Sandbox Code Playgroud)

  • FWIW,即使在 iOS 10 中,我也有同样的问题。在下一个运行循环中,大小是正确的。手动调整大小是唯一的解决方案。 (2认同)