How to create horizontally dynamic UICollectionView cells? Swift

我怕爱的太早我们不能终老 提交于 2019-12-02 02:23:20

You need unambiguous constraints between your label and the cell (e.g. leading, trailing, top, and bottom constraints):

Then you can use UICollectionViewFlowLayoutAutomaticSize for the itemSize of your collectionViewLayout. Don't forget to set estimatedItemSize, too, which enables automatically resizing cells:

override func viewDidLoad() {
    super.viewDidLoad()

    let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
    layout.itemSize = UICollectionViewFlowLayoutAutomaticSize
    layout.estimatedItemSize = CGSize(width: 100, height: 40)
}

That yields:

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); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!