2

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?

Community
  • 1
  • 1
Ali
  • 9,800
  • 19
  • 72
  • 152

2 Answers2

2

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.

MikeCocoa
  • 306
  • 2
  • 7
  • I read somewhere using `[views lastObject]` is safer than objectAtIndex:0. do you know why? in this answer: http://stackoverflow.com/questions/9648076/how-to-design-separate-uiview-outside-of-any-viewcontroller-in-storyboard – Ali Sep 26 '12 at 09:15
  • 1
    I'd imagine that views lastObject would just return null if there were no objects where objectAtIndex:0 will crash your program. – MikeCocoa Sep 26 '12 at 14:30
0

You can try with:

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

And then:

[self.scrollView addSubview:[temporaryController view]];
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
CSolanaM
  • 3,138
  • 1
  • 20
  • 21
  • does not work. Apps crashed! did you implement something like this or it was just your guess? – Ali Sep 24 '12 at 21:19
  • Uhm I've done this with UITableViewCells in that way: UITableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"NameNIBCell" owner:self options:nil] objectAtIndex:0]; – CSolanaM Sep 24 '12 at 21:28