views:

42

answers:

1

Hi, am having the following problem:

In my app I am creating a temporary object, for example a label in the following way:

UILabel *tempLabel = [ [UILabel alloc] initWithFrame: CGRectMake(100, 5, 200, 30)];
tempLabel.backgroundColor = [UIColor colorWithRed: 1.0f green: 1.0f blue: 1.0f alpha: 0.0f];
tempLabel.text = [ [WordsDatabase sharedWordsDatabase] dbName];

[ [self view] addSubview: tempLabel];
[tempLabel release];

This code is being called from the viewWillAppear method.

When the view itself is being called for the first time, everything is fine. But for the second time, the newer label seems to get overlapped by the old one.

Are there any steps to be taken in order to make this effect disappear? Something to add into the viewWillDisappear method?

I tried to add declaration of a label into the class interface and in the viewWillDisappear method to call [label removeFromSuperview]. And in this case everything is fine. Is there a way to have this done without storing a reference to a label?

Thank you in advance.

A: 

You can sort your subviews by using the sortSubviewsUsingFunction:context: method. One way to implement this is by adding a tag (UIView's tag property) with a integer value to each subview. You can then sort by tag like this (assuming tag is a number):

Sort function:

int viewObjectSortByTag(NSControl *firstView, NSControl *secondView, void *context) {
    return ([firstView tag] > [secondView tag]) ? NSOrderedAscending : NSOrderedDescending;
}

After adding a subview just sort the views:

[[self view] sortSubviewsUsingFunction:&viewObjectSortByTag context:nil];
Diederik Hoogenboom