A
A
Alex Rubera2017-02-20 12:04:33
iOS
Alex Rubera, 2017-02-20 12:04:33

How to calculate cell width for UICollectionView?

There is only one element inside the cell - UILabel. Approximately as in the picture:
071b4c44ebc845f48029244ee9fd5fd4.png
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

2 answer(s)
A
Alexander, 2017-02-20
@alexyat

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

at the end, floorf is needed so that there is no blending when rendering.
use like this
maxTextHeight - just in case there are not too large cells.
sizeForText: - text for which we consider
withFont: - font that we will use
withWidth: - label width

M
ManWithBear, 2017-02-20
@ManWithBear

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 question

Ask a Question

731 491 924 answers to any question