Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create view from a nib file in xcode?

I have the following code to create a view and put it in scrollview to allow paging
the code works fine however what I couldn't do is loading views from a nib file

in other words I want to use "initWithNibName" instead of "initWithFrame"?

   - (void)createPageWithColor:(UIColor *)color forPage:(int)page
     {
     UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, 300,400)];
         newView.backgroundColor = color;
     [scrollView addSubview:newView];
    }

Thanks alot

like image 462
ahmed Avatar asked Jun 21 '10 23:06

ahmed


2 Answers

Try something like this (adapted from "The iPhone Developers Cookbook", pg. 174):

UIView *newView = [[[NSBundle mainBundle] loadNibNamed:@"yournib" owner:self options:nil] lastObject];

This assumes a single view object in your .xib, but you could modify it if your .xib is more complicated.

like image 107
Cheddar Avatar answered Sep 20 '22 02:09

Cheddar


I know this is an old post, but I wanted to create a UIView as a separate file and add a xib so I could use it in several places in my app (almost like using it as a custom table view cell). And I couldn't get it quite right, but this post helped me get to the result I wanted.

So just if anyone wants to do it the same way, this is what I did:

Add this to the initialization code in your UIView's .m file:

- (id)initWithFrame:(CGRect)frame
{
    self = [NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil][0];
    if (self)
    {
        self.frame = frame;
    }
    return self;
}

Then in interface builder/xib editor you have to assign the class you created for the UIView so you can add IBOutlets.

Hope it helps someone out, cuz it took me a bit!

like image 32
Matt W. Avatar answered Sep 22 '22 02:09

Matt W.