How to create horizontally dynamic UICollectionView cells? Swift

后端 未结 2 1836
忘掉有多难
忘掉有多难 2021-01-22 00:03

Hey I\'m trying display a set of \"tags\" in a view controller using collection view cells but I\'m having trouble finding a way to make them be able to dynamically resizable de

2条回答
  •  佛祖请我去吃肉
    2021-01-22 00:37

    You can calculate the lengths of the texts ahead of time, feed them into an array accessible by your collectionView and use them them to construct the size of the cell.

    //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;
    

    Create the size of the cell using some code like this:

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

提交回复
热议问题