views:

69

answers:

3

I add a label on to the view UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 320.0f, 300.0f, 75.0f)]; [titleLabel setText:[BusinessLogic instance].homeMessage];

then I move to another view and come back. This results in having two label controls on top of each other. What I want to do is: check if the label control has been added already. If not add it and set the text. If it is, just set the text.

What's the best way to do it. I want to learn the proper way as I have already a couple of disgusting ideas of how to do it.

Thanks. mE

+3  A: 

You can check the superview property:

if (titleLabel.superview == self) {
}

(assuming "self" is the view you're adding the label to)

Philippe Leybaert
i'd say, he should move the UILabel variable outside the function first. Then check if nil or not.
CiNN
I agree with CiNN - thanks guys
amok
+1  A: 
if (titleLabel.superview != someView) {
    [someView addSubview:titleLabel];
}
nduplessis
+1  A: 

Add a property to your class to store a reference to your label. If you don't store it anywhere, you can't change its text easily in the future:

// header
@property (nonatomic, retain) IBOutlet UILabel *titleLabel;
// implementation
@synthesize titleLabel;

Create the UILabel instance if titleLabel is nil and assign to it:

if (self.titleLabel == nil) {
   UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 320.0f, 300.0f, 75.0f)];
   self.titleLabel = titleLabel;
   [titleLabel release];
   // add to the view here.
}
self.titleLabel.text = newText;
Mehrdad Afshari
small typo: @synthesis -> @synthesize
Philippe Leybaert