Question

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

Was it helpful?

Solution

You can check the superview property:

if (titleLabel.superview == self) {
}

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

OTHER TIPS

if (titleLabel.superview != someView) {
    [someView addSubview:titleLabel];
}

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top