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

Chr*_*att 5 iphone objective-c ios uicollectionview

我有一个UICollectionView带有不同大小标签的单元格.我正在尝试根据标签的大小调整单元格的大小.然而sizeForItemAtIndexPath,我创建单元格的地方似乎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);
}
Run Code Online (Sandbox Code Playgroud)

Fay*_*007 13

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)
    }
Run Code Online (Sandbox Code Playgroud)

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

  • 不要忘记将`UICollectionViewDelegateFlowLayout`添加到类继承中. (2认同)

Pra*_*tel -1

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

templable.test = @"asdasdhasjdhajkdh";

templable.numberOfLines = 0;

[templable sizeToFit];

float width = 0;

width = self.templable.bounds.size.width+20;
Run Code Online (Sandbox Code Playgroud)