Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS5 Assign a .xib to a custom UIView class

HI have a custom view class that is loaded and placed within my main view using the following code. The reason it that i want to populate it with different content so rather than build a view in code each time if I create a custom class i can reuse this in a loop etc, I got this to work just fine in code, that is laying out the buttons label etc.

But rather than hand code it all I thought if i create a new User Interface View, then construct visually my text fields, labels and buttons on this view.

Then connect it to my custom class.

Bu this is where I am having an issue, how do I connect this view xib file so that it becomes visible when placed on my my code. I have assigned the custom class attribute within the xib file to my custom file, but what else am i missing?

.h File:

 #import <UIKit/UIKit.h>

 @interface blogView : UIView

 @end

.m File:

 #import "blogView.h"

 @implementation blogView

 - (id)init
 {
     self = [super initWithFrame:CGRectMake(0, 0, 478, 220)];
     if (self != nil)
     {
         NSLog(@"Blog View loaded");

         self.backgroundColor = [UIColor yellowColor];

         UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 400, 40)];
         [titleLbl setText:@"This is the Title"];

         [self addSubview:titleLbl];

     }
     return self;
 }

 @end

my xib file has the same name blogView.xib which is a View User Interface.

Within my main view controller and in the ViewDidLoad i have

  blogView *blogItem = [[blogView alloc]init];
  [self.view addSubview:blogItem];

When I run this is all works fine, but I would like to link to a .xib file to save time etc. Thanks

like image 571
Simon Davies Avatar asked Feb 01 '12 23:02

Simon Davies


2 Answers

Well having look around and trying bits of clues and suggestion I managed to do this with the following:

Within my .m file I placed/Changed the following:

  self = [super init];
  if (self != nil)
      {      
          NSArray *theView =  [[NSBundle mainBundle] loadNibNamed:@"blogView" owner:self options:nil];
          UIView *nv = [theView objectAtIndex:0];

    .. rest of code.

   [self addSubview:nv];

 .. rest of code.

Many Thanks

like image 166
Simon Davies Avatar answered Oct 05 '22 22:10

Simon Davies


I struggled with this for an hour when I RENAMED my viewcontroller class. This is what worked for me in Xcode 5

  1. Go to your XIB file
  2. Click on Files owner transparent box on the left
  3. Open up your inspections tab(Third button on right in the View Section - in between Editor and Organizer)
  4. Go to your identity Inspector(3rd from the left) underneath the editor organizer view tab.
  5. Fix the custom class - Class option to whatever class you want it to respond to.

Lets just say I was extremely annoyed after wasting time with that

like image 39
Leon Avatar answered Oct 05 '22 22:10

Leon