Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UIView added in the interface builder does not load the xib

Tags:

I have created custom UIView with a xib.

In addition I have a UIViewController in my storyboard, to which I have added a UIView and set its class to be my custom UIView.

But when I am running the app, the view doesn't have its subviews. When I debug, all the subviews are null.

In .m of the custom UIView, these init methods are present:

- (id)initWithFrame:(CGRect)frame {     self = [super initWithFrame:frame];     if (self) {      }     return self; }  - (id)initWithCoder:(NSCoder *)aDecoder {     self = [super initWithCoder:aDecoder];     if (self) {      }     return self; } 

What am I missing?

like image 966
Luda Avatar asked Dec 01 '13 07:12

Luda


People also ask

How do I load a nib in Swift?

mainBundle(). loadNibNamed("SomeObject", owner: self, options: nil) self. addSubview(self. view); // adding the top level view to the view hierarchy } required init(coder aDecoder: NSCoder) { super.


1 Answers

As you already know, with a UIViewController we have the -initWithNibName:bundle: method to connect it with an xib.
But...
When it comes to a UIView, you need to use -loadNibNamed:owner:options: and load it with the xib. (simply specifying a custom class to the view in the xib won't work)


Suppose:

  1. Created a UIView subclass called CustomXIBView
    • (New File > Cocoa Touch > Objective-C Class -- Subclass of UIView)
  2. Created a Simple View User Interface and named it CustomXIBView
    • (New File > User Interface > View)

Steps:

  1. Go to CustomXIBView's nib
  2. Select View (left toolbar)
  3. Select Show Identity Inspector (3rd option in the panel on the right)
  4. Specify CustomXIBView as the Custom Class of the View
    • don't do anything with CustomXIBView's File's Owner in the nib
  5. Drag Drop Objects and connect it with CustomXIBView.h

Code:

//To load `CustomXIBView` from any `UIViewController` or other class:  //instead of the following commented code, do the uncommented code //CustomXIBView *myCustomXIBViewObj = [CustomXIBView alloc] init]; //[myCustomXIBViewObj setFrame:CGRectMake(0,0,320,480)];  //Do this: CustomXIBView *myCustomXIBViewObj =       [[[NSBundle mainBundle] loadNibNamed:@"someView"                                     owner:self                                   options:nil]                             objectAtIndex:0]; [myCustomXIBViewObj setFrame:CGRect(0,                                      0,                                      myCustomXIBViewObj.frame.size.width,                                      myCustomXIBViewObj.frame.size.height)]; [self.view addSubview:myCustomXIBViewObj]; 

ref: http://eppz.eu/blog/uiview-from-xib/

like image 142
staticVoidMan Avatar answered Oct 21 '22 09:10

staticVoidMan