I have a view controller that is instantiated in开发者_Go百科 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.
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.
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.
[self.view viewWithTag:NUMBER_OF_TAG];
does the trick. But remember that if you want to access the view you must do it on the viewWillAppear or viewDidAppear events.
精彩评论