0

I have a custom cell in storyboard. I've set iPhone 4.7 inch in storyboard for the viewController that contains its tableView.

Since I want to lay out some UIImageViews in a scrollView that is inside this cell, I need to know the width of the cell. I'm trying to get this width inside the layoutSubviews, like following:

-(void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat cellWidth = self.contentView.bounds.size.width;
}

It gets called multiple times, and when I run it on iPhone 5 the first two times are not correct(it's 375 which is what it is on the storyboard, and afterward it's 320 which is the correct size)

How do I get the real width of the cell, anyway?

Thanks in advance.

Erfan
  • 143
  • 10

2 Answers2

0

Auto Layout Disabled?

-(void)layoutSubviews will work fine and give your expected height, width if the cell is not auto layout supported.

Auto Layout Enabled?

Override this to adjust your special constraints during a constraints update pass

- (void)updateConstraints
{
  [super updateConstraints];

  CGFloat cellWidth = CGRectGetWidth(self.bounds);
  NSLog(@"cellWidth %f", cellWidth);
}

Hope this will work!

Shamim Hossain
  • 1,690
  • 12
  • 21
  • Thanks for your answer; but updateConstraints gets called once and cellWidth that it returns is 375, which is not correct. – Erfan Oct 31 '15 at 07:19
0

Ultimately the fact is that UIKit can call layoutSubviews any number of times. You just have to assume that each time will be the last, and take steps to avoid repeating work. E.g. cache self.bound.size from the prior call and only proceed if it's changed.

Or you can set up constraints on the scroll view and the image views and not worry about manual layout.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • I need to lay out multiple image view programatically, since I get their images from the Internet. So I should layout based on the current self.bound.size and once a new one received remove all the subviews of the scrollview and redo lay out the image views again? – Erfan Oct 31 '15 at 07:16
  • No, you should be smart and only remove the views that no longer fit. Or use a `UICollectionView` and let it worry about what fits. Check out the App Store app: horizontally scrolling collection views inside a vertically scrolling view. – rob mayoff Oct 31 '15 at 07:40