1

I'm building a status item kind of thing for a UICollectionView. My problem is when I want to add some text to the status area I can't get the thing to auto resize to the new text. I have auto layout on and I've tried all kinds of things found on stacky.

The one which I think is the closest to being correct is this:

-(UICollectionViewCell *) collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    StatusItemModel *statusModel = [self.items objectAtIndex[indexPath indexPosition:0]];
    StatusItemEventCell *statusCell = [collectionView dequeueResusableCellwithReuseIdentifier: @"EventStatusItem" forIndexPath:indexPath];

    statusCell.statusTitleLabel.text = [statusModel.statusDetails valueForKey:@"title"];
    statusCell.statusContentTextView.text = [statuaModel.statusDetails valueForKey:@"content"];
    [statusCell layoutIfNeeded];
    return statusCell;
}

// After which I believe we have to do some magic in this but what?

- (CGSize) collectionView:(UiCollectionView *) collectionView layout:(UICollectionViewLayout *) collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // How do I get the size of the textview statusContentTextView.text?
    // With that I'll be able to figure out what needs to be returned.
    return CGSizeMake(299.f, 200.f);
}

The autolayout is setup with constraints for all elements in the cell. I've even played around with the intrinsic size and placeholders, however still now luck. Please can someone point me in the right direction.

Larme
  • 24,190
  • 6
  • 51
  • 81
Sententia
  • 625
  • 1
  • 6
  • 17
  • take a look at this. Hope it might help you http://stackoverflow.com/questions/7754851/autoresizing-masks-programmatically-vs-interfact-builder-xib-nib – Silviu St Apr 25 '14 at 10:40

1 Answers1

1

So after going around in circles thinking there was a better way, no we need to know the size before we can set the size of the cell for the collection view. Pretty counter productive, because sometimes we don't know the size of it at run time. The way I solved this was to create a mock UITextView object and then called sizeThatFits.

So here is what I did with my code:

- (CGSize) collectionView:(UICollectionView *) collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    StatusItemModel *statusModel = [self.items objectAtIndex:[indexPath indexAtPosition:0]];
    UITextView *temporaryTextView = [[UITextView alloc] init];
    temporaryTextView.text = [statusModel.statusDetails valueForKey:@"content"];
    CGSize textBoxSize = [temporaryTextView sizeThatFits:CGSizeMake(299.0f, MAXFLOAT)];
    // Can now use the height of the text box to work out the size of the cell and
    // the other components that make up the cell
    return textBoxSize;
}
Sententia
  • 625
  • 1
  • 6
  • 17