我有一个应用程序,使用
添加到superview的子视图很少 [self.view addSubview:subview.view];
所有都是不同的视图控制器,并具有自定义后退按钮以返回主/第一视图。到现在为止没有问题。
在应用程序的某些部分,我必须从屏幕/子视图4跳转到第一个视图,在那里我重新创建第一个视图。 (使用initWithNibName和addSubview)。这会增加应用程序的内存。
要解决此问题,我想删除所有子视图并返回第一个视图,因为它已经存在但不可见,而不是再次创建第一个视图。
如何实现这一目标?
请帮忙。
提前致谢
答案 0 :(得分:2)
您可以声明特定视图的代码值,并根据需要删除所有视图:
* for([self.view subviews]中的UIView *子视图)
{
if(view isKindOfClass:[UIView class])
{
if (subview.tag == 101 || subview.tag == 102)
{
[subview removeFromSuperview];
}
}
} *
此行下面有一个示例代码:在此代码按钮'btn'由xib创建,并调用btnClicked方法
- (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];
}
答案 1 :(得分: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];
}
}