0

我有以下情况: 在此处输入图像描述

是在SecondViewController里面FirstViewController。现在,我想向 中添加另一个子类FirstViewController,但要从secondViewController该类中添加,如图所示:在此处输入图像描述

我一直在寻找,我认为这是不可能的。我已经尝试实例化 FirstViewController,访问“视图到子视图”并添加为子视图,但这不起作用:

FirstViewController *viewController = [[FirstViewController alloc] init];
[self.view addSubview:[viewController viewToAddAsSubView]];

任何提示/解决方案?

谢谢!

4

2 回答 2

3

这实际上可以使用 NSNotificationCenter。下面的例子:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(METHOD:) name:@"LISTEN_TO_VIEW_2" object:nil];

上面的代码应该放在视图 1 中,以便“监听”视图 2 向它发送一个通知,通知您应该执行视图 1 中的方法以在视图 1 中添加/编辑您想要的任何内容。

[[NSNotificationCenter defaultCenter] postNotificationName:@"LISTEN_TO_VIEW_2" object:nil];

上面的代码会将通知发送到视图 1。然后在视图 1 中,您将有一个类似这样的方法:

-(void)METHOD:(id)sender {
//do something here
}
于 2012-08-01T02:37:10.703 回答
0

一种可能的方法是使用 SecondViewController 的视图的 superView。这是一种非常直接的方式。

[[self.view superview] insertSubview:theView aboveSubview:self.view];

另一种方法是使用委托。您可以在 SecondViewController 中声明一个委托,例如

@protocol SecondViewControllerDelegate : NSObject
{
    - (void)requestInsertView:(UIView*)view aboveView:(UIView*)baseView;
}

@interface SecondViewController <...>

@property (nonatomic, assign) id<SecondViewControllerDelegate>superViewDelegate;
@end;

并修改FirstViewController的声明实现SecondViewControllerDelegate

@interface FirstViewController <SecondViewControllerDelegate, ...> 

@implement FirstViewController

- (void)requestInsertView:(UIView*)view aboveView:(UIView*)baseView
{
    [self.view insertView:view aboveSubview:baseView];
}
@end;

创建 SecondViewController 后,将其 superViewDelegate 设置为 FirstViewController 的实例。

在您需要从 SecondViewController 添加视图的地方,您可以调用

[self.superViewDelegate requestInsertView:view aboveView:self.view];
于 2012-08-01T03:42:38.563 回答