如何创建半透明模态UIViewController?

时间:2009-09-30 16:37:18

标签: iphone cocoa-touch

我想创建一个可重用的UIViewController子类,它可以显示为任何其他视图控制器上的模态视图控制器。这个可重用的VC需要做的第一件事就是弹出一个UIActionSheet。为此,我在VC中创建了一个默认(空白)视图,以显示来自的工作表。

然而,这看起来很糟糕,因为当弹出模态vc时,隐藏了父vc。因此,看起来动作表漂浮在空白背景上。如果动作表可能看起来弹出原始(父)vc。

会更好

有没有办法实现这个目标?简单地抓住父vc的视图并从中激活UIActionSheet是否安全?

3 个答案:

答案 0 :(得分:14)

在您的模态视图设置为动画后,其大小将调整为与其父视图相等。你可以做的是在viewDidAppear:中,拍摄parentController的视图,然后在你自己的视图的子视图列表后面插入一个包含父图片的UIImageView:

#pragma mark -
#pragma mark Sneaky Background Image
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // grab an image of our parent view
    UIView *parentView = self.parentViewController.view;

    // For iOS 5 you need to use presentingViewController:
    // UIView *parentView = self.presentingViewController.view;

    UIGraphicsBeginImageContext(parentView.bounds.size);
    [parentView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *parentViewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // insert an image view with a picture of the parent view at the back of our view's subview stack...
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView.image = parentViewImage;
    [self.view insertSubview:imageView atIndex:0];
    [imageView release];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    // remove our image view containing a picture of the parent view at the back of our view's subview stack...
    [[self.view.subviews objectAtIndex:0] removeFromSuperview];
}

答案 1 :(得分:0)

您可以通过在父视图中插入视图来简单地在父视图控制器上显示它。

这样的事情:

PseudoModalVC *vc = ...//initialization
vc.view.backgroundColor = [UIColor clearColor]; // like in previous comment, although you can do this in Interface Builder
vc.view.center = CGPointMake(160, -vc.view.bounds.size.height/2);
[parentVC.view addSubView:vc.view];

// animation for pop up from screen bottom
[UIView beginAnimation:nil context:nil];
vc.view.center = CGPointMake(160, vc.view.bounds.size.height/2);
[UIView commitAnimation];

答案 2 :(得分:-1)

是的。将它添加到当前视图控制器的视图中(或作为窗口的子视图)并在屏幕上为其设置动画,就像Valerii所说。

要用动画删除它,请执行此操作(我假设模态视图为320 x 460,它将从屏幕上滑落):

- (void)dismissModal
{
    // animate off-screen
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView setAnimationDuration:0.50];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    self.view.frame = CGRectMake( 0, 480, 320, 460 );

    [UIView commitAnimations];
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    // don't remove until animation is complete. otherwise, the view will simply disappear
    [self.view removeFromSuperview];
}