user4487951
user4487951

Reputation:

Add subview to a xib file

I'm trying to add a label to a UIView in a xib file. When I run the app, the label doesn't shows up.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];
    [self.label setText:@"This is a label"];

    xibView *myxibView = [[xibView alloc] init];
    [myxibView.myView addSubview:self.label];
}

Upvotes: 0

Views: 801

Answers (3)

Vineesh TP
Vineesh TP

Reputation: 7973

Simply add ,

self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];
[self.label setText:@"This is a label"];
[self.view addSubview:self.label];

It will subView the label on the view.

Upvotes: 0

JackYe
JackYe

Reputation: 122

1.If your controller has the same name with your xib, For example,XibViewController.m & XibViewController.xib. Your controller will set its view to an instance of XibViewController.xib by default.

On this condition, you just need to add the label to the self.view

[self.view addSubview:self.label];

2.If you want to load the XibViewController.xib to an different name controller like View2Controller.m, you need load the xib by name and and add the xib view to View2Controller's view.

UIView *myxibView = [[[NSBundle mainBundle] loadNibNamed:@"XibViewController" owner:self options:nil] objectAtIndex:0];
[myxibView addSubview:self.label];
[self.view addSubview:myxibView];

Upvotes: 2

Rashad
Rashad

Reputation: 11197

xibView *myxibView = [[xibView alloc] init];
[myxibView.myView addSubview:self.label];

You didn't added myxibView to actual view. Its just an instance. Why don't you do this:

 [self.view addSubview:self.label];

Hope this helps.. :)

Upvotes: 0

Related Questions