Ios UICollectionView,带有一个带有sizeToFit的UILable

Ios UICollectionView,带有一个带有sizeToFit的UILable,ios,objective-c,uilabel,uicollectionview,uicollectionviewcell,Ios,Objective C,Uilabel,Uicollectionview,Uicollectionviewcell,我在一个名为CollectionViewCell的类的UICollectionViewCell中有一个UILabel,它的所有功能都在工作。但是当UILabel小于我想要输入的文本时,问题就来了 我已经做了[cell.label sizeToFit];在cellForItemAtIndexPath中 -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(

我在一个名为CollectionViewCell的类的UICollectionViewCell中有一个UILabel,它的所有功能都在工作。但是当UILabel小于我想要输入的文本时,问题就来了

我已经做了[cell.label sizeToFit];在cellForItemAtIndexPath中

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

   NSDictionary *news = [self.select objectAtIndex:indexPath.row];

   CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

   cell.label.text = [news objectForKey:@"content"];
   [cell.label setFont:[UIFont systemFontOfSize:15]];
   cell.label.numberOfLines = 0;
   [cell.label sizeToFit];
   cell.label.preferredMaxLayoutWidth = 292.f;
   return cell;
}
已经做出了这样的约束,它只对前7个单元格有效,其他单元格的高度为29,下面是我实现的代码,用于生成单元格变量的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    int h = 29 + cell.label.frame.size.height;
    return CGSizeMake(292, h);
}

这是一些it工作的结果

如果这是使用UICollectionViewFlowLayout,则必须实现
collectionView:layout:SizeFormiteIndeXPath:
。这就是你必须测量的地方

现代技术是使用自动布局约束并调用
systemLayoutSizeFittingSize:
来计算单元格大小。下面是实际代码:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    self.modelCell.lab.text = self.sectionData[indexPath.section][indexPath.row]
    var sz = self.modelCell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
    sz.width = ceil(sz.width); sz.height = ceil(sz.height)
    return sz
}

请注意,这意味着您必须在
collectionView:layout:sizeForItemAtIndexPath:
(进行测量)和
CellForItemIndexPath:
(使标签内容显示在实际单元格中)中提供标签内容。

您是否尝试过这行代码[cell.label sizeToFit];collectionview?@Dev的单元格出列后,我已将该单元格放在问号中索引路径的第行。否,返回单元格大小的是sizeForItemAtIndexPath。可以从代码中发布-(UICollectionViewCell*)cellForItemAtIndexPath:(NSIndexPath*)indexPath方法吗。它必须在您的代码中。对于完整的示例,请参见我尝试在collectionView:layout:sizeForItemAtIndexPath:中设置label.text,但没有结果,我在问题中添加了一个图像以使其更清晰,但下载了我指给您的项目。这是关于使用不同大小的标签,它的工作。