1

I have an app which has few subviews added to superview using

 [self.view addSubview:subview.view]; 

All are different view controllers and have custom back buttons to come back to main/first view. Until now no issue.

At some of in the app I have to jump from screen/subview 4 to first view, where I recreate first view. (using initWithNibName and addSubview). This increases a memory of the app.

To solve this, I want to remove all subviews and come back to first view as it already exists but is not visible instead of creating first view again.

How to achieve this?

Please help.

Thanks in advance

4

2 回答 2

2

您可以声明特定视图的标签值,并根据需要删除所有视图:

*for (UIView *subview in [self.view subviews])

{

if(查看 isKindOfClass:[UIView 类])

{

 if (subview.tag == 101 || subview.tag == 102) 

{

 [subview removeFromSuperview];

}

}

}*

此行下方有一个示例代码:在此代码中,由 xib 创建并调用 btnClicked 方法的按钮“btn”


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    myViewNew = [[UIView alloc] initWithFrame:CGRectMake(50, 40, 150, 150)];
    [myViewNew setTag:102];
    [myViewNew setBackgroundColor:[UIColor redColor]];

    myView = [[UIView alloc] initWithFrame:CGRectMake(50, 40, 150, 150)];
    [myView setTag:101];
    [myView setBackgroundColor:[UIColor blueColor]];

    btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn1 setFrame:CGRectMake(50, 50, 50, 50)];
    btn1.titleLabel.text = @"btn1";
    [myView addSubview:btn1];

    [btn1 addTarget:self action:@selector(btn11Pressed:) forControlEvents:UIControlEventTouchUpInside];

    btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn2 setFrame:CGRectMake(50, 50, 50, 50)];
    btn2.titleLabel.text = @"btn2";
    [myViewNew addSubview:btn2];

    [btn2 addTarget:self action:@selector(btn2Pressed) forControlEvents:UIControlEventTouchUpInside];


}

-(void)btn2Pressed
{
     for (UIView *subview in [self.view subviews])
     {
       if(view isKindOfClass:[UIView class])

       {

        if (subview.tag == 101 || subview.tag == 102) 
        {
            [subview removeFromSuperview];
        }
       }

      }
}

-(void) btn11Pressed:(id)sender
{
    [self.view addSubview:myViewNew];
}

-(IBAction)btnClicked:(id)sender
{
    [self.view addSubview:myView];
}
于 2012-06-19T04:50:13.637 回答
0

如果您想删除所有子视图并使用 firstview:

  //here view where you want remove all sub views containing in view
  [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperView)];

这样做以保持一个子视图可见:

    NSArray *allSubViews = [self.view subviews];
    for(int i= 0; [allSubViews count];i++)
    {
      if(i !=0)
      {
          UIView *view = [allSubViews objectAtIndex:i];
          [view removeFromSuperview];
      }
    }
于 2012-06-19T04:17:20.890 回答