Adding a custom subview (created in xib) to the view controller view - what am I doing wrong

I created a view in xib (with an activity indicator, a progress view and a label). Then I created .h / .m files:

#import <UIKit/UIKit.h> @interface MyCustomView : UIView { IBOutlet UIActivityIndicatorView *actIndicator; IBOutlet UIProgressView *progressBar; IBOutlet UILabel *statusMsg; } @end #import "MyCustomView.h" @implementation MyCustomView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { // Initialization code } return self; } - (void)dealloc { [super dealloc]; } @end 

In IB, I set the file owner and viewed it in MyCustomView and connected the IBOutlet to the file owner

In MyViewController.m I have:

 - (void)viewDidLoad { [super viewDidLoad]; UIView *subView = [[MyCustomView alloc] initWithFrame:myTableView.frame]; [subView setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5]]; [myTableView addSubview:subView]; [subView release]; } 

When I launch the application, the view is added, but I do not see the label, progress bar and activity indicator.

What am I doing wrong?

+59
ios objective-c xib addsubview
Mar 18 2018-11-18T00:
source share
3 answers

You need to load it using the -loadNibNamed method. -initWithNibName is for UIViewControllers only.

Add the following code to the MyCustomView initialization method:

 NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil]; UIView *mainView = [subviewArray objectAtIndex:0]; [self addSubview:mainView]; 

Remember that if you initialize an object from nib, it calls - (id)initWithCoder:(NSCoder *)aDecoder to initialize, so you will have to override this if you create a MyCustomView object in nib. If you just do this with initWithFrame: just override this and add the code above. Also, in your tip, make sure you have one top-level UIView and put all the other elements in it (which ensures that your subviewArray has only one entry).

This will load the views from nib and add them to the object and will do the trick.

+129
Mar 18 2018-11-18T00:
source share

I think you need to use this method:

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil; 

This is because you need to pass the .xib file name to "nibNameOrNil".

+1
Mar 18 '11 at 16:09
source share

As hocker said, you should use this method passing the XIB name (without extension).

Then you need to manage this list:

  • Open the .xib file in IB
  • Click "File Owner" and select the correct class (MyCustomView in your case).
  • Hold down the control button and drag it from File Owner to View (now the output for the view is fine)

Hope this works. Greetings.

0
Mar 18 '11 at 20:26
source share



All Articles