隐藏不同视图控制器的子视图

Posted

技术标签:

【中文标题】隐藏不同视图控制器的子视图【英文标题】:Hide subview of different view controller 【发布时间】:2010-11-30 16:48:34 【问题描述】:

我有一个视图作为另一个自定义警报视图的背景(浅灰色 0.5 alpha)。

当用户点击自定义警报上的“确定”按钮时,我还想隐藏自定义警报和背景视图。

两个视图都是同一个父视图的子视图...

我在 buttonTapped: 方法中执行此操作以隐藏视图,并且它在第一次尝试时有效,但从第二次开始,后台视图永远不会关闭...警报每次都正确隐藏。

[UIView animateWithDuration:0.5f animations:^
    self.view.alpha=0.0f; //hide alert
    [self.view.superview viewWithTag:1].alpha=0.0f; //hide background       
];

它们被添加为子视图,如下所示:

ResultDialogController *dialogController = [[[ResultDialogController alloc] initWithNibName:@"ResultDialogController_" bundle:nil] retain];
ResultBackgroundViewController *bgViewController = [[[ResultBackgroundViewController alloc] initWithNibName:@"ResultView" bundle:nil] retain];

dialogController.view.alpha=0;
bgViewController.view.alpha=0;
bgViewController.view.tag=1;

[UIView animateWithDuration:0.5f animations:^
    bgViewController.view.alpha=0.5f;                                       
    dialogController.view.alpha=1.0f;
    ];

[self.view addSubview:bgViewController.view];
[self.view addSubview:dialogController.view];
[dialogController release];
[bgViewController release];

我怎样才能总是关闭背景视图?

谢谢

【问题讨论】:

【参考方案1】:

您似乎没有删除视图,您只是通过将 alpha 设置为零来使视图不可见。因此,每次调用第二个代码示例时,都会将新版本的背景视图和对话框视图添加到 self.view。在第二次调用中,您将有两个背景视图,它们的标签 = 1 并且您从对 [self.view.superview viewWithTag:1] 的调用中获得了您的第一个背景视图,这就是您新添加的背景视图不会变得不可见的原因。

但这还不是全部,ResultDialogControllerResultBackgroundViewController 也存在内存泄漏。当您调用initWithNibName:bundle: 时,不需要调用retain。也许您这样做是因为您在释放控制器时发生了一些崩溃?

您应该做的是为您的控制器创建 ivars 和属性。

@property (nonatomic, retain) ResultDialogController *resultController;
@property (nonatomic, retain) ResultBackgroundController *backgroundController;

然后在显示控制器时,您可以执行以下操作:

ResultDialogController *dialogController = [[ResultDialogController alloc] initWithNibName:@"ResultDialogController_" bundle:nil];
self.dialogController = dialogController;

ResultBackgroundViewController *bgViewController = [[ResultBackgroundViewController alloc] initWithNibName:@"ResultView" bundle:nil];
self.backgroundController = bgViewController;

// do the same as before

然后在buttonTapped: 你这样做:

[UIView animateWithDuration:0.5f
     animations: ^
      self.dialogController.view.alpha = 0;
      self.backgroundController.view.alpha = 0;
     
     completion: ^(BOOL finished)
      [self.dialogController.view removeFromSuperview];
      [self.backgroundController.view removeFromSuperview]; 
     
 ];

最重要的是,不要忘记在 dealloc 中释放控制器 ivars。

【讨论】:

非常感谢,尽管进行了一些编辑...在您的animateWithDuration:0.5f 之后,您有不应该存在的duration 一词。完成块处理程序也应该是completion: ^(BOOL finished) 【参考方案2】:

您可以通过将视图的 HIDE 属性设置为 true 来隐藏它们。

【讨论】:

以上是关于隐藏不同视图控制器的子视图的主要内容,如果未能解决你的问题,请参考以下文章

UINavigationBar 子视图隐藏了正确的 UIBarButtonItem

你真的可以将约束链接到完全不同的视图控制器吗?

根视图控制器的子视图控制器位于根之上

处理包含能够折叠和展开的子视图的视图

关于使用navigationController,前后2个视图控制器navigationBar隐藏属性不同,导致右滑手势失效问题的解决办法

在Scroll View的高度动画后,UIScrollView的子视图不响应触摸