简体   繁体   中英

How to load UILabel from UIView?

I have a problem with UILabel and UIView. In my UIViewController I load a 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. How can i load also this UILabel and change the text?

Thanks

You can tag the UILabel inside of the .xib file and then access the UILabel like this:

(Assume you have tagged the UILabel 42 )

UILabel *label = [detail viewWithTag:42];

You can then change the text as you would with any other 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. 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)
  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

Arguably option 2 is the best from that list as it is the best containment of knowledge and the most reusable.

In the XIB file you can create an outlet to the file's owner. 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).

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