Clearing a subview


#1

If you want to clear the content of a subview, is there a command for this, or is deleting the subview and creating a new one a better way to handle it? In the chapter section on adding labels, I was wondering how one would go about clearing the subview every time you entered text into the text field instead of the results just piling up on top of each other. I tried a quick search through the documentation in Xcode and Google, but did not see anything off the bat that helped. Anyone know?

edit: Seems I wrote this too soon. Each time you enter text in the text field it is creating a new subview, yes? So then you would have to go and delete the previous subview in order to only show one text entry at a time if I understand it correctly.


#2

So the first thing I want to point out is that our goal in that section was to keep adding new labels to the screen. Later in the book, we end up animating the new labels onto the screen. But let me answer your question.

There is absolutely a way to do this, but we really need a reference to the labels in order to update their text contents. (You can see earlier in the chapter the way to clear the text of a label, which is by setting the text to @"". In textFieldShouldReturn:, you can see that on the line of code that says textField.text = @"":wink:

The way I’d approach this is to keep a mutable array of all of the labels that we add to the screen. I’d add this in the class extension.

@property (nonatomic) NSMutableArray *labels;

Then when we add the labels to the screen in drawHypnoticMessage:, we’d add the labels to that array.

...
// Add the label to the hierarchy
[self.view addSubview:messageLabel];

// NEW CODE: Add the label to our new array
[self.labels addObject:messageLabel];

Now that we have all of the hypnotic labels in an array, we can iterate over the array to do whatever we want:

for (UILabel *label in self.labels) {
    label.text = @""; // Or whatever you want to do here
}

That should give you the building blocks you need to do what you want. You’ll most likely need to update other code (probably drawHypnoticMessage:), depending on exactly what you want to do. Let me know if you have any other questions!