根据标签大小调整UICollectionViewCell的大小 [英] Sizing UICollectionViewCell Based on label Size

查看:100
本文介绍了根据标签大小调整UICollectionViewCell的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UICollectionView ,其中包含不同大小标签的单元格。我正在尝试根据标签的大小调整单元格的大小。但是 sizeForItemAtIndexPath 我创建单元格的地方似乎在 cellForItemAtIndexPath 之前调用我在哪里设置标签..任何想法我是什么可以在这里做什么?

I've got a UICollectionView that will have cells with labels of varying sizes. I'm trying to size the cell based on the size of the label. However sizeForItemAtIndexPath where I create the cell seems to be called before cellForItemAtIndexPath where I set the label.. Any ideas what I can do here?

- (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 我已经计算了标签的文本大小并根据它更新了单元格大小:

In swift i have calculated the text size of label and updated the cell size according to it:

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

as i have an extra button and padding i calculated that extra value which is 45.0

这篇关于根据标签大小调整UICollectionViewCell的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆