I am using 2 UIView to draw different objects in a xib file. There is a need to clear the view before drawing new objects for some actions. Initially,when object types are smaller in number, I have been using this:
for (UILabel *btn in self.contentView.subviews)
{
if([btn isKindOfClass:[UILabel class]])
{
[btn removeFromSuperview];
}
}
But when I have multiple actions and objects of multiple types are to be drawn for each action, it looks bad coding to use this type of method. Is there some efficient method to do this?
For UIView, you can safely use makeObjectsPerformSelector: because the subviews property will return a copy of the array of subviews. Using makeObjectsPerformSelector method you can remove all the subviews but, not subviews based on conditions.
Managing Subviews To remove an arranged subview that you no longer want around, you need to call removeFromSuperview() on it. The stack view will automatically remove it from the arranged subview list.
I found this was because the self. subviews was mutated (maybe) when the removeFromSuperview() was called. By doing . copy(), I could perform the removal of each subview while mutating the self.
You should use this to remove all subviews, regardless of their class.
[self.contentView.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With