sensslen
sensslen

Reputation: 780

add View loaded from xib into a UIScrollview

I'm trying to add a View created through a xib File into a UIScrollview.

The View looks like that: View setup in Interface Builder

What I get is: The View added to a UIScrollview in code

The Code I use to add the View to the UIScrollview (which is setup in Storyboard) is:

Initialisation code:

NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"SpuelungProtokollView" owner:self options:nil];
HPSpuelungProtokollView * spuelungProtokollView = [subviewArray objectAtIndex:0];
HPSpuelung * vInfo = pInfo;

// setup Infos
// ... this part is not related to the problem ...

[self setContentView:spuelungProtokollView];

and then I do the following in viewDidLoad::

[[self scrollView] setContentSize:[[self contentView] frame].size];
[[self scrollView] addSubview:[self contentView]];
[[self contentView] layoutIfNeeded];

Has anybody had a similar Problem - know how to properly add a (properly constraint) UIView to UIScrollview?

Thanks in Advance for Answers!

EDIT

A strange Side Effect is: the View loads correctly if I put the view Hirarchy is created in viewDidAppear:

Upvotes: 2

Views: 2819

Answers (2)

sensslen
sensslen

Reputation: 780

I've been able to resolve the Issue - I had to set the Autoresizing Mask of the custom View in initWithCoder: like that:

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

    return self;
}

Hope this helps somebody else....

Upvotes: 1

Bejmax
Bejmax

Reputation: 945

You should implement awakeFromNib: to initialize the view. If you aren't, then it's probably not getting setup properly.

NSNibAwaking Protocol Reference: This informal protocol consists of a single method, awakeFromNib. Classes can implement this method to initialize state information after objects have been loaded from an Interface Builder archive (nib file).

So, i think you'd want something like the following for your impl:

- (void)awakeFromNib {
    [[self scrollView] setContentSize:[[self contentView] frame].size];
    [[self scrollView] addSubview:[self contentView]];
    [[self contentView] layoutIfNeeded];
    return;
}

awakeFromNib is actually special in that it's part of the NSNibAwaking informal protocol (basically means that your object doesn't have to conform to it). What happens is when an object is loaded from a nib file (.xib) it will be sent this message once all the outlets are connected as long as it implements the awakeFromNib method.

Upvotes: 1

Related Questions