How to use a xib and a UIView subclass together?

12,552

Yes that's the way that it works when you're loading xibs that aren't parents to viewControllers

Edit August 15, 2013:

You can't always just assume that you're going to get exactly what you're looking for out of index 0 of the returned NSArray, which is what makes it good to use type checking.

NSArray *xibArray = [[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:nil options:nil];
MyCustomView *myView = nil;
for (id xibObject in xibArray) {
//Loop through array, check for the object we're interested in.
    if ([xibObject isKindOfClass:[MyCustomView class]]) {
        //Use casting to cast (id) to (MyCustomView *)
        myView = (MyCustomView *)xibObject;
    }
}
Share:
12,552
Ron
Author by

Ron

Updated on June 03, 2022

Comments

  • Ron
    Ron almost 2 years

    I'd like to create a couple of custom views, sort of reusable UI components, and would prefer to not layout the UI in code in the UIView subclass. I'd like to use a xib for that. I've used a xib by itself. And I've used a UIView subclass by iteself. But I haven't used them together. How do I "attach" them to one another? I'd like to use IBOutlets to access the UILabels in my custom view.

    Will this kind of thing work?

    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil]; 
    MyCustomView *view = [xib objectAtIndex:0];
    view.myLabel.text = @"fred";
    
  • Ron
    Ron over 13 years
    I did get this to work the way I wanted it to. I created the UIView subclass, added the IBOutlets for the two UILabels I have. In Interface Builder I changed the view class to my UIView subclass, and set the referencing outlets on my two labels to the view.
  • Greg
    Greg almost 13 years
    I'm trying to do the same thing - Do you know what classname I should be using for (a) parent UIControllerView and (b) the custom UIView itself here? I've noted in my code I have my custom UIView class name in both but that giving me a recursive call to my custom UIView init method. That is I have (a) in the parent UIControllerView which uses my custom view, in IB for it's XIB I use a UIView which I've set the classname to "clockview", but then (b) in my actual clockview custom UIView (not UIControllerView) XIB file I've done the same thing and set the class name to be "clockview".
  • Daddy
    Daddy almost 12 years
    I don't understand what you mean. It's less time consuming to make a UI layout in Interface Builder, connect some IBOutlets than it is to manually set CGRect frames