简体   繁体   English

如何从UIView加载UILabel?

[英]How to load UILabel from UIView?

I have a problem with UILabel and UIView. 我对UILabel和UIView有问题。 In my UIViewController I load a UIView: 在我的UIViewController中,我加载一个UIView:

NSArray *first = [[NSBundle mainBundle] loadNibNamed:@"customView" owner:self options:nil];
UIView *detail = [first objectAtIndex:0];

Inside the Xib of the UIView that i have already loaded (@"customView") there is a UILabel. 我已经加载的UIView的Xib(@“ customView”)中有一个UILabel。 How can i load also this UILabel and change the text? 我如何也可以加载此UILabel并更改文本?

Thanks 谢谢

You can tag the UILabel inside of the .xib file and then access the UILabel like this: 您可以在.xib文件中标记UILabel,然后按以下方式访问UILabel

(Assume you have tagged the UILabel 42 ) (假设您已标记UILabel 42

UILabel *label = [detail viewWithTag:42];

You can then change the text as you would with any other UILabel : 然后,您可以像使用任何其他UILabel一样更改文本:

label.text = @"Text for the label";

If in the XIB the root view has a subview then that is also loaded when you load the XIB. 如果在XIB中,根视图具有子视图,则在加载XIB时也会加载该子视图。 You have a few options for connecting to it: 您可以选择几种连接方式:

  1. Add an outlet to the file owner in the XIB (this is your view controller) 在XIB中向文件所有者添加出口(这是您的视图控制器)
  2. Add an outlet to the root view that the view controller can use to get the label 向根视图添加出口,视图控制器可使用该出口获取标签
  3. Use the tag on the label and viewWithTag: to search for it 使用tag上的标签和viewWithTag:进行搜索

Arguably option 2 is the best from that list as it is the best containment of knowledge and the most reusable. 可以说,选项2是该列表中的最佳选项,因为它是对知识的最佳控制和最可重复使用的。

In the XIB file you can create an outlet to the file's owner. 在XIB文件中,您可以创建文件所有者的出口。 Then you can access the property of the view controller, since it is the file's owner of the XIB (set in your first line of code). 然后,您可以访问视图控制器的属性,因为它是XIB的文件所有者(在第一行代码中设置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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