Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In iOS, how do I reference an object in a view that is created with a xib file?

I have a view controller that is instantiated in appDelegate and pushed onto a navigation controller. The view controller's view is created with a xib file. The xib file puts a UILabel on the view (among other things). Now I need to set the label's text property programatically but I don't see how to get a reference to it. How do I reference the label object?

I'm using xcode 3.2.5 and building an iPad app.

like image 730
RobertL Avatar asked Jan 22 '11 02:01

RobertL


2 Answers

Aside from IBOutlets, you can also set a tag property on the label in the IB. Then, when you need it you can do:

UILabel *label = (UILabel *)[self.view viewWithTag:111];

111 of course being the tag you assigned to the label in IB.

like image 191
tux91 Avatar answered Nov 15 '22 19:11

tux91


You do this with what's called an "outlet". You define them in your controller, mark them clearly as IBOutlet and then connect them in Interface Builder to your file owner (or other delegate object created in IB).

For instance, in your FooController.m you might have this:

@interface FooController ()
@property (nonatomic, weak) IBOutlet UILabel* fooLabel;
@end

Then you would select your label, and either control drag from it to the file owner, or go to its connections tab, and drag from the + under referencing outlet, to the file owner and select the fooLabel.

UPDATE: Code sample changed to reflect modern way of handling this case.

like image 45
jer Avatar answered Nov 15 '22 18:11

jer