How to remove subviews in Objective-C?

廉价感情. 提交于 2019-12-02 21:16:59

I assume you're calling [self.view removeFromSuperView] from a method in the same class as the above snippet.

In that case [self.view removeFromSuperView] removes self.view from its own superview, but self is the object from whose view you wish to remove subviews. If you want to remove all the subviews of the object, you need to do this instead:

[notesDescriptionView removeFromSuperview];
[button.view removeFromSuperview];
[textView removeFromSuperview];

Perhaps you'd want to store those subviews in an NSArray and loop over that array invoking removeFromSuperview on each element in that array.

mac

to remove all the subviews you added to the view

use the following code

for (UIView *view in [self.view subviews]) 
{
    [view removeFromSuperview];
}
Erik van der Neut

I've always been surprised that the Objective-C API doesn't have a simple method for removing all sub views from a UIView. (The Flash API does, and you end up needing it quite a bit.)

Anyway, this is the little helper method that I use for that:

- (void)removeAllSubviewsFromUIView:(UIView *)parentView
{
  for (id child in [parentView subviews])
  {
    if ([child isMemberOfClass:[UIView class]])
    {
      [child removeFromSuperview];
    }
  }
}

EDIT: just found a more elegant solution here: What is the best way to remove all subviews from you self.view?

Am using that now as follows:

  // Make sure the background and foreground views are empty:
  [self.backgroundContentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
  [self.foregroundContentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

I like that better.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!