Question

I need an example of how to instantiate a custom view from a nib file. i wrapped my head around several stackoverflow posts but i didn't get it. Maybe i only need a hint how to do it.

what I want to do is - creating a custom view with interface builder. it should be a template so that i can instantiate it multiple times to add it to multiple view controllers.

So far I have created my custom view xib file called MyIssueView.xib. Which consists in fact just of the main view and some labels.

And I created a Subclass of UIView which is called IssueView with the Outlets for my labels in the MyIssueView.xib.

How do I now hook up the outlets with the IB? And how can I instantiate the IssueView from any ViewController?

Would be glad for an example! Cheers.

UPDATE:

I now have

IssueView.xib IssueView.h (UIView Subclass) IssueView.m

My IssueView.h:

#import <UIKit/UIKit.h>

@interface IssueView : UIView

@property (weak, nonatomic) IBOutlet UILabel *label1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (weak, nonatomic) IBOutlet UILabel *label3;
@property (weak, nonatomic) IBOutlet UILabel *label4;

@end

My IssueView.m:

#import "IssueView.h"

@implementation IssueView
@end

My ViewController.m:

#import "AllIssuesViewController1.h"
#import "IssueView.h"
#import "UIView+NibLoading.h"

@interface AllIssuesViewController1 ()

@end

@implementation AllIssuesViewController1


- (void) loadView
{

}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _issueView = [IssueView loadInstanceFromNib];
}

It gives me an error:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x8292580> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label1.'
Was it helpful?

Solution

I have a category that extends UIView called UIView+NibLoading.

In it is this code...

#import "UIView+NibLoading.h"

@implementation UIView (NibLoading)

+ (id)loadInstanceFromNib
{
    UIView *result;

    NSArray* elements = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil];

    for (id anObject in elements) {
        if ([anObject isKindOfClass:[self class]]) {
            result = anObject;
            break;
        }
    }

    return result;
}

@end

Then when I want to instantiate a UIView subclass from a nib I just import the category and I can run...

self.issueView = [IssueView loadInstanceFromNib];\

You need to connect the labels like this...

enter image description here

If you connecting the labels to "File's Owner" then you'll need to remove those connections.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top