如何创建水平动态UICollectionView单元格?迅速

时间:2017-08-07 17:22:58

标签: ios swift uicollectionview uicollectionviewcell

嘿我正在尝试展示一组"标签"在视图控制器中使用集合视图单元格,但我无法找到一种方法使它们能够根据字符串的长度动态调整大小。

现在,单个单元格的大小是静态大小的,因此只要字符串填充单元格的字符超过单元格的大小,就会进入第二行。我想要它,以便单元格可以根据字符串的长度更改长度。因此,如果它是#34;#Vegan"标签,它会自动调整大小以使标签不那么大。同样,如果它是一个更长的字符串,如#34;#LaptopFriendly",它将水平变长以容纳字符串而不使用第二行。垂直长度可以保持固定。谢谢!

enter image description here

UPDATE(使用Rob代码遇到错误时的界面构建器设置):

enter image description here

模拟器截图: enter image description here

2 个答案:

答案 0 :(得分:12)

您的标签和单元格之间需要明确的约束(例如,前导,尾随,顶部和底部约束):

enter image description here

然后,您可以将UICollectionViewFlowLayoutAutomaticSize用于itemSize的{​​{1}}。不要忘记设置collectionViewLayout,这样可以自动调整单元格大小:

estimatedItemSize

产量:

enter image description here

答案 1 :(得分:0)

您可以提前计算文本的长度,将它们提供给collectionView可访问的数组,并使用它们构建单元格的大小。

//Create vars
NSArray * texts = @[@"Short",@"Something Long",@"Something Really Long"];
NSMutableArray * lengths = [NSMutableArray new];
float padding = 30.0f;

//Create dummy label
UILabel * label = [UILabel new];
label.frame = CGRectZero;
label.font = [UIFont systemFontOfSize:20.0f weight:UIFontWeightBold];

//loop through the texts
for (NSString * string in texts){

    //set text
    label.text = string;

    //calculate length + add padding
    float length = [label.text boundingRectWithSize:label.frame.size
                                            options:NSStringDrawingUsesLineFragmentOrigin
                                         attributes:@{NSFontAttributeName:label.font}
                                            context:nil].size.width + padding;
    //save value into array as NSNumber
    [lengths addObject:@(length)];
}

//drop label
label = nil;

使用如下代码创建单元格的大小:

return CGSizeMake(lengths[indexPath.row], 100.0f);