How to use a xib and a UIView subclass together?

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";

Answers


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;
    }
}

Need Your Help

Coding my own function constructor for a string object

javascript string function object constructor

I am working through the exercises in the book Object-Oriented JavaScript by Stoyan Stefanov. The exercise is asking me to create a function constructor for a String object. None of the built-in St...

Do interfaces have toString method?

java interface

How is it possible to call toString method using the reference variable of interface My, which does not have a toString method?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.