How to remove subviews in Objective-C?

前端 未结 3 1130
小鲜肉
小鲜肉 2021-02-01 16:47

I have added UIButton and UITextView as subviews to my view programmatically.

notesDescriptionView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,460)];
notes         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 17:52

    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.

提交回复
热议问题