3

I have sub-classed uiscrollview and used initWithCoder to prepare my uiscrollview with all the subviews. I have used below code to set it up:

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {

    NSLog(@"%f", self.frame.size.height);

    self.contentSize = CGSizeMake(5000, self.frame.size.height);

    labelContainerView = [[UIView alloc] init];
    labelContainerView.frame = CGRectMake(0, 0, self.contentSize.width, self.contentSize.height/2);
    labelContainerView.backgroundColor = [UIColor yellowColor];
    [self addSubview:labelContainerView];
}

But this keeps failing because the self.frame property always return 0 values. Its super important for me to use self.frame property because I want to use storyboard to do any height adjustments for the frame of the scrollview.

I have tried the same thing using xib files instead of using the storyboard and it works fine. But in my project I dont want to use xib files.

It'll be really great if anyone can explain me why I get 0 values in initWithCoder: method when I use storyboard? and if using storyboard how to achieve this?

PS: I notice layoutSubviews method return correct frame information but I cannot create my subviews here since it get called for each frame change (when I scroll)

Monolo
  • 18,205
  • 17
  • 69
  • 103
niroshan
  • 181
  • 10
  • Check out this answer: http://stackoverflow.com/questions/12758782/how-can-i-set-the-size-of-a-uiview-init-with-storyboard/15892101#15892101 – AndrewCr Apr 09 '13 at 02:11
  • A trick that seems to work: http://stackoverflow.com/a/5837133/294884 – Fattie Mar 30 '14 at 16:39

1 Answers1

3

Are you using Autolayout in your Storyboard?

If you are really not taking advantage of it, you can disable it and your -initWithCoder: method will return your frame again.

If you do need Autolayout, try the following:

-(void)awakeFromNib
{
    [super awakeFromNib];

    [self setNeedsLayout];
    [self layoutIfNeeded];

    // self.frame will now return something :)
}
iOSCowboy
  • 1,426
  • 2
  • 9
  • 9