将子视图添加到xib文件 [英] Add subview to a xib file
问题描述
我正在尝试在xib文件中为UIView添加标签。当我运行应用程序时,标签不显示。
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.如果您的控制器有与你的xib同名,
例如,XibViewController.m& XibViewController.xib。
默认情况下,您的控制器会将其视图设置为XibViewController.xib的实例。
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.
在这种情况下,您只需要将标签添加到self中。查看
On this condition, you just need to add the label to the self.view
[self.view addSubview:self.label];
2.如果要将XibViewController.xib加载到其他名称控制器(如View2Controller.m),你需要按名称加载xib,并将xib视图添加到View2Controller的视图中。
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];
这篇关于将子视图添加到xib文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!