我有一个主视图,如图所示。我在其中添加了2个子视图,每个子视图都有自己的视图控制器。
在ipadMainViewController
中,
self.dTVC= [[dialoguesTableViewController alloc] initWithNibName:@"dialoguesTableViewController" bundle:nil];
[self.dTVC.view setFrame:rectFordTVC];
[self.view addSubview:self.dTVC.view];
之后,如果我按
dialoguesTableViewController
中的按钮,我想删除CategoriesViewController
的视图。但是,我无法将其删除。在
CategoriesViewController
中,我这样写,但是dialoguesTableViewController
无法从ipadMainViewController
中删除。我该怎么做?在
CategoriesViewController
中,我编写了这样的代码,但是它不起作用。self.dTVC= [[dialoguesTableViewController alloc] initWithNibName:@"dialoguesTableViewController" bundle:nil];
[self.dTVC.view removeFromSuperview];
最佳答案
因此,有几种方法可以做到:
第一种方式:
将观察者添加到ipadMainViewController初始化方法或viewDidLoad方法中,具体取决于您的需求。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(buttonPressed)
name:@"kNotificationDidPressedButon"
object:nil];
将
-buttonPressed
方法添加到ipadMainViewController控制器以删除视图或其他目的。- (void)buttonPressed
{
// remove view here
}
在您单击相应按钮的方法中的CategoriesViewController中,添加以下代码:
[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationDidPressedButon"
object:self];
第二种方式:
将委托属性添加到CategoriesViewController。您可以在此处找到有关如何委派代表的信息:link
第三方式:
使用Objective-C块
对于初学者的初步建议:
我建议您从第一种方式开始,因为这是最简单的理解方法。此外,您还必须在ipadMainViewControllerr中的
-dealloc
或-viewWillDisapper
方法中删除观察者,这取决于您在何处添加观察者,例如在-init
方法中或在-viewDidLoad
或-viewWillAppear
回调中;[[NSNotificationCenter defaultCenter] removeObserver:self];