Ali
Ali

Reputation: 9994

Add .xib file to a ViewController in storyboard

I am somehow new in iPhone development.

I have a storyboard that includes a ViewController. inside the ViewController, I have a UIScrollView.

I want to add two images and other controls to my scrollView. I read this link, and decide to implement the idea that described as the answer, but not the way he did programmatically.

I create a new .xib file and then add a UIView to it and add my UIImages and Labels in it.

Now, I want to add this UIView to my UIScrollView in the storyboard. This is my code:

OfferUIView *newPageView = [[OfferUIView alloc] init];
self.newPageView.contentMode = UIViewContentModeScaleAspectFill;
newPageView.frame = frame;
[self.scrollView addSubview:newPageView];
[self.pageViews replaceObjectAtIndex:page withObject:newPageView];

It does not work for my UIView which is a .xib file, but simply if I add for instance a UIImageView like:

UIImageView *newPageView = [[UIImageView alloc] initWithImage:image];
self.newPageView.contentMode = UIViewContentModeScaleAspectFill;
newPageView.frame = frame;
[self.scrollView addSubview:newPageView];
[self.pageViews replaceObjectAtIndex:page withObject:newPageView];

Then it perfectly works. So how can I fix my code to add .xib file?

Upvotes: 2

Views: 6724

Answers (2)

CSolanaM
CSolanaM

Reputation: 3368

You can try with:

UIViewController *temporaryController = [[UIViewController alloc] 
                                          initWithNibName:@"NameOfXIB" 
                                                   bundle:nil];

And then:

[self.scrollView addSubview:[temporaryController view]];

Upvotes: 0

MikeCocoa
MikeCocoa

Reputation: 296

The Answer that Carlos gave probably should work with 1 tweak. It sounds to me like your .xib file might contain just an UIView rather than an UIViewController. If that is the case you would need to do something more like:

NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"NameOfXIB" owner:self options:nil];
UIView *view = [views objectAtIndex:0];

Either that or you would need to change the .xib file to contain an UIViewController, but it doesn't sound like that is quite what you are after.

Upvotes: 2

Related Questions