Reputation: 99
I have a ViewController
and a View
in separate files.
In the ViewController
I add the View like this:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
mainView = [[MainView alloc] init];
[self setView: mainView];
}
return self;
}
In that mainView
there is a label, added as SubView
. I would like to change the labels text from my controller. How would I do that?
I can't figure out how to access the label from the controller.
Upvotes: 1
Views: 1172
Reputation: 17231
If mainView
has only the label as a subview and no other subviews you can easily access the label with
UILabel *label = (UILabel *)[mainView.subviews objectAtIndex:0];
and then set its text like this:
label.text = @"your text";
That is the "quick and dirty" way.
A much better solution is to create a property
in your ViewController
for each subview that you want to modify. CTRL+drag the label to your ViewController.h
file and Xcode should automatically add the line
@property (strong, nonatomic) IBOutlet UILabel *label;
Then you can easily access the label from anywhere in your ViewController
with
label.text = @"your text";
Upvotes: 0
Reputation: 8905
Another method.
In MainView.m tag your label where you are creating it
yourLabel.tag = 'urlb'
In your ViewController
UILabel *lbl = (UILabel *)[mainView viewWithTag:'urlb'];
[lbl setText: @"what is the problem"];
Upvotes: 0
Reputation: 781
The label needs to be exposed in the MainView as e.g. a property.
Then you can access that property like:
[[(MainView *)[self view] labelProperty] setText: @"foo"];
Or more readable:
MainView *mainView = (MainView *)self.view;
mainView.labelProperty.text = @"foo";
Upvotes: 1