0

I just want to load a custom view (with xib) on a viewcontoller's xib or stroy board.What is the best practice to do the same.

I have used awakeAfterUsingCoder function code below.

(id) awakeAfterUsingCoder:(NSCoder*)aDecoder
{
    BOOL theThingThatGotLoadedWasJustAPlaceholder = ([[self subviews] count] == 0);
    if (theThingThatGotLoadedWasJustAPlaceholder)
    {
        CustomView* theRealThing = (id) [CustomView view];
        theRealThing.frame = self.frame;
        theRealThing.autoresizingMask = self.autoresizingMask;
        return theRealThing;
    }
    return self;
}

but after using this function my awakeFromNib started calling multiple time.

Please sugegst.

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65

1 Answers1

0

The correct answer currently linked to is overly complicated and buggy, as you have found out. There is a much more standard and better way to do this:

  1. Create an empty XIB
  2. Add a UIView to your XIB so that it is the only top-level object (aside from the proxies First Responder and File's Owner)
  3. Change the class of your new UIView to CustomView
  4. Instantiate the XIB and retrieve your CustomView instance like so:

    CustomView *view = [[UINib nibWithNibName:@"CustomView" bundle:nil] instantiateWithOwner:self options:nil][0];

  5. Add it to your view hierarchy in your view controller's viewDidLoad method:

    [self.view addSubview:view];

Be sure to override -initWithCoder: in your CustomView subclass in case you need to do any custom initialization. I know this is a lot, so please let me know of any if these steps confuse you or if you get stuck.

Dany Joumaa
  • 2,030
  • 6
  • 30
  • 45