根据标签大小调整UICollectionViewCell的大小

我有一个UICollectionView ,它将具有不同大小标签的单元格。 我正在尝试根据标签的大小调整单元格的大小。 但是我创建单元格的sizeForItemAtIndexPath似乎是在我设置标签的cellForItemAtIndexPath之前cellForItemAtIndexPath的。任何想法我能在这做什么?

 - (void)getLabelSize:(UILabel *)label { float widthIs = [label.text boundingRectWithSize:label.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:label.font } context:nil].size.width; width = widthIs; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { // Configure the cell UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; UILabel *label = (UILabel *)[cell viewWithTag:1000]; label.text = @"This is pretty long"; [label sizeToFit]; [self getLabelSize:label]; NSLog([NSString stringWithFormat:@"%f", width]); cell.backgroundColor = [UIColor whiteColor]; return cell; } - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { return CGSizeMake(width, 50); } 

swift中,我计算了标签的文本大小,并根据它更新了单元格大小:

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let size: CGSize = keywordArray[indexPath.row].size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)]) return CGSize(width: size.width + 45.0, height: keywordsCollectionView.bounds.size.height) } 

因为我有一个额外的按钮和填充我计算了额外的值45.0

您需要在某个位置存储标签的文本,例如,在数组中,并单独定义标签的字体并定义maxWidth,如:

 #define kLabelFont [UIFont fontWithName:@"SourceSansPro-Regular" size:12.0f] #define maxWidth 100.0f 

然后使用string作为参数修改方法getLabelSize:

 - (CGSize)getLabelSize:(NSString *)string { CGRect rect = [string boundingRectWithSize:(CGSize){maxWidth, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName: kLabelFont } context:nil]; return rect.size; } 

然后你可以从两个方法获取cellForItemAtIndexPath和sizeForItemAtIndexPath的大小:

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { ........ NSString *string = [self.textArray objectAtIndex:indexPath.row]; CGSize size = [self getLabelSize:string]; ........ } 

首先,您必须将消息存储在临时标签中(确保它隐藏或不可见)。 然后得到标签的宽度和高度如下:

 templable.test = @"asdasdhasjdhajkdh"; templable.numberOfLines = 0; [templable sizeToFit]; float width = 0; width = self.templable.bounds.size.width+20;