Answer the question
In order to leave comments, you need to log in
How to calculate cell width for UICollectionView?
There is only one element inside the cell - UILabel. Approximately as in the picture:
The text in this UILabel can be different, therefore, it is impossible to know the width in advance. I saw options with calculating the width of the text, using the title and font size. But I don't want to be tied in the code to the style of the elements.
In the controller, sizeForItemAt is called before cellForItemAt, i.e. before the actual text appears in the UILabel. Therefore, the real size in sizeForItemAt cannot be calculated.
What is the correct algorithm for solving this problem? Why sizeForItemAt at all, if you can fill it with only some fixed values for all cells.
Answer the question
In order to leave comments, you need to log in
here is the method to calculate text height
+(CGFloat)sizeHeightForText:(NSString *)text withFont:(UIFont *)font withWidth:(float)width
{
CGSize constraint = CGSizeMake(width, 20000.0f);
CGSize size = [text sizeWithFont:font
constrainedToSize:constraint
lineBreakMode:NSLineBreakByWordWrapping];
return floorf(size.height)+1;
}
Alexander
's version works, but is terrible.
Ideally, you need to create and store somewhere an empty cell, into which you throw all the data for the calculation, tell it [cell sizeToFit] (as a variant of sizeThatFits), then return its dimensions.
In general, look towards https://github.com/Instagram/IGListKit from Instagram.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question