无法删除子视图控制器

时间:2014-05-03 09:35:31

标签: ios objective-c

我正在尝试在函数didSelectRowAtIndexPath中添加子视图控制器。但我无法删除我添加的这个子视图控制器。这就是我的尝试:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath  *)indexPath
  {

    MiddleViewController *middleVC =[self.storyboard instantiateViewControllerWithIdentifier:@"MiddleViewController"];



  if(isMenuExpanded==NO){

    isMenuExpanded=YES;
   middleVC.view.hidden=FALSE;
[middleVC.view setFrame:CGRectMake(-320, 0, self.view.frame.size.width, self.view.frame.size.height)];



[self addChildViewController:middleVC];
[self.view addSubview:middleVC.view];
[middleVC didMoveToParentViewController:self];

  [UIView animateWithDuration:0.3 animations:^{
    [middleVC.view setFrame:CGRectMake(38, 0, self.view.frame.size.width, self.view.frame.size.height)];


   }];

}else{
    isMenuExpanded=NO;


    //here i am trying to remove the child view controller
     middleVC.view.hidden=TRUE;
    [middleVC willMoveToParentViewController:nil];
    [middleVC.view removeFromSuperview];
    [middleVC removeFromParentViewController];



     }
  }

我也尝试隐藏了视图控制器。

3 个答案:

答案 0 :(得分:2)

请找到更改,你也可以这样做

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath  *)indexPath
{

    MiddleViewController *middleVC =[self.storyboard instantiateViewControllerWithIdentifier:@"MiddleViewController"];

   if(isMenuExpanded==NO)
{

    isMenuExpanded=YES;
    middleVC.view.hidden=FALSE;
    [middleVC.view setFrame:CGRectMake(-320, 0, self.view.frame.size.width, self.view.frame.size.height)];


    **middleVC.view.tag=8010;**
    [self addChildViewController:middleVC];
    [self.view addSubview:middleVC.view];
    [middleVC didMoveToParentViewController:self];

    [UIView animateWithDuration:0.3 animations:^{
        [middleVC.view setFrame:CGRectMake(38, 0, self.view.frame.size.width, self.view.frame.size.height)];


    }];

}
else
{
    isMenuExpanded=NO;

    **for(UIView *view in [self.view subviews])
    {
        if(view.tag == 8010)
           [view removeFromSuperview];
    }**
}

答案 1 :(得分:1)

您无法隐藏它,因为每次点击您的单元格时都会创建MiddleViewController的新实例。

您需要做的是,全局声明MiddleViewController *middleVC(您可以在课程的.h文件中声明它) -

-(void)viewDidLoad
{
     MiddleViewController *middleVC =nil;
}

并在您的didSelect方法中 - 替换此行 -

MiddleViewController *middleVC =[self.storyboard instantiateViewControllerWithIdentifier:@"MiddleViewController"];

使用此代码 -

if(middleVC == nil) {
     middleVC =[self.storyboard instantiateViewControllerWithIdentifier:@"MiddleViewController"];
}

答案 2 :(得分:1)

在我看来,当您点击时,您正试图切换"菜单视图"(middleVC),但为什么每次都要创建一个新实例?我看到的是你试图隐藏尚未添加到视图中的内容。

如果我是你,我会将实例化部分从didSelectRowAtIndexPath(到viewDidLoad或其他东西)中取出并保留引用。