0
votes

I am trying to create a custom UIView and have it load in a xib file. The custom UIView is called JtView and here is the code:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    NSLog(@"initWithFrame was called");  // this was called
    if (self) {
        // Initialization code
        [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:NULL];
        [self addSubview:self.view];
    }
    return self;
}

-(void)awakeFromNib
{
  [super awakeFromNib];
  [self addSubview:self.view];
}

In creating the xib file (File -> New -> File -> User Interface -> View), I deleted out the main Window and dragged a View from Xcode's object pallette. I tried alt-dragging to the header for JtView but this wasn't working. Do I need to create an association here or should I just leave what XCode created in place? (edit - see comments below for further clarification)

I have also added a UILabel to the xib.

However, when I run in simulator and set the background color to red, the label is not showing up. Do I need to create the UILabel as a reference in the custom UIView? Should I be deleting this or leaving it in place? enter image description here

thx

edit 1 Here's a screenshot of the connections and the header file:

2
Please check file's owner of the View in nib file. You must mention JtView in place of file owner of view in nibabdus.me
so yes, I've adjusted and not deleted out the main Window. I've hooked up the file's owner to the View but the label is still not showing up.timpone
okay. If you have not yet solved your problem please refer to Question stackoverflow.com/questions/15144482/… It might be helpful. Please revert to me in case of any problem. Thanksabdus.me

2 Answers

1
votes

I solve it adding a class method to the UIView:


+ (id)customView;

+ (id)customView
{
    CustomView *customView = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:nil options:nil] lastObject];

    // make sure customView is not nil or the wrong class!
    if ([customView isKindOfClass:[CustomView class]])
        return customView;
    else
        return nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    CustomView *customView = [CustomView customView];
    //And where you gonna use it add this line:
    //this self.view refers to any view (scrollView, cellView...)
    [self.view addSubview:customView];
}

I hope it´s gonna help

-1
votes

Try this:

-(void)awakeFromNib {
    NSArray *obj = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
    [self addSubview:obj[0]];
}

Or if you have an @property IBOutlet named "nibview" you could do:

-(void)awakeFromNib {
    [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
    [self addSubview:self.nibview];
}