简体   繁体   中英

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

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];
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.. :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM