Add subview to a xib file

本小妞迷上赌 提交于 2019-12-02 20:04:22

问题


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:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/28289999/add-subview-to-a-xib-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!