如何正确使用"sendSubviewToBack"方法?

man*_*esh 8 iphone objective-c uiviewcontroller uiview ios

我已经实现了幻灯片菜单,但我想要像facebook一样的滑动效果.我遇到了关于stackoverflow的帖子:

使用目标c的iphone facebook侧面菜单

我想在其中实施greenisus给出的解决方案(上调了15次),但我在实施时遇到了麻烦,Bot在评论中提出了同样的问题."@ greenisus我对如何将菜单发送到后面感到困惑?当我这样做时,它只显示一个黑色的侧面菜单." 没有得到回答.

他的答案可供参考:

这真的很简单.首先,您需要创建一个位于可见的视图控制器下面的视图控制器.您可以将该视图发送到后面,如下所示:

[self.view sendSubviewToBack:menuViewController.view];
Run Code Online (Sandbox Code Playgroud)

然后,在导航栏的左侧放置一个菜单按钮,并编写一个类似于此的处理程序:

- (void)menuButtonPressed:(id)sender {
    CGRect destination = self.navigationController.view.frame;
    if (destination.origin.x > 0) {
        destination.origin.x = 0;
    } else {
        destination.origin.x += 254.5;
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.navigationController.view.frame = destination;        
    } completion:^(BOOL finished) {
        self.view.userInteractionEnabled = !(destination.origin.x > 0);
    }];
}
Run Code Online (Sandbox Code Playgroud)

这是一般的想法.您可能必须更改代码以反映您的视图层次结构等.

只是想知道什么时候我们必须使用下面的方法,第二种方法很简单,工作正常,但不显示菜单视图.

[self.view sendSubviewToBack:menuViewController.view];
Run Code Online (Sandbox Code Playgroud)

寻找一些指针或解决方案来正确运行上面的代码.

sun*_*ppy 2

其实你应该知道我们该怎么做。只需添加 menuViewController.view 作为 self.view 的子视图。但这将覆盖 navigationController.view,因此您可以只 [self.view sendSubviewToBack:menuViewController.view]。当您需要显示/隐藏 menuViewController 时,您需要使用方法 - (void)menuButtonPressed:(id)sender。

在 HomeViewController 中:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // be careful with the sequence of the code. If you firstly add the contentViewController and then add the 
    // menuViewController you need to [self.view sendSubviewToBack:self.menuViewController.view], else you don't
    // need to use sendSubviewToBack.
    self.menuViewController = [[MenuViewController alloc] init];
    self.contentViewController = [[ContentViewController alloc] init];
    [self.view addSubview:self.menuViewController.view];
    [self.view addSubview:self.contentViewController.view];
}
Run Code Online (Sandbox Code Playgroud)

在内容视图控制器中:

- (IBAction)showMenu:(id)sender
{
    CGRect destination = self.view.frame;
    if (destination.origin.x > 0) {
        destination.origin.x = 0;
    } else {
        destination.origin.x += 254.5;
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.view.frame = destination;        
    } completion:^(BOOL finished) {
        //self.view.userInteractionEnabled = !(destination.origin.x > 0);
    }];
}
Run Code Online (Sandbox Code Playgroud)