以编程方式将另一个 UIViewController 显示为 iOS 中的弹出窗口?

Programmatically showing another UIViewController as popup in iOS?

我有主仪表板 (UITableViewController),登录后我需要使用 UIViewController.

显示带有欢迎消息的页面

如何从我的 ViewDidAppear() 方法中显示此弹出窗口?

我正在使用以下代码,但它不起作用

  -(void)viewDidAppear:(BOOL)animated{
        popupObj= [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
        [popupObj setModalPresentationStyle:UIModalPresentationCurrentContext];
    }

请帮帮我..

我看到了几个 Whosebug 链接

更新

当我将代码更改为这个时

-(void)viewDidAppear:(BOOL)animated{
    popupObj= [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
   // [popupObj setModalPresentationStyle:UIModalPresentationCurrentContext];
    popupObj.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    popupObj.modalTransitionStyle = UIModalPresentationPopover;
    [self presentViewController:popupObj animated:YES completion:nil];
}

现在我可以看到我的 UIViewController 作为弹出窗口出现,但现在 UIViewController 以全屏视图出现。

但我只需要这个frame (320 , 320)

您的代码创建了视图控制器并设置了它的呈现样式,但实际上并没有呈现它。为此,您需要在您现在拥有的两行之后添加此行:

[self presentViewController:popupObj animated:true completion:nil];
popupObj= [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
popupObj.view.frame = CGRectMake(20, 200, 280, 168);
[self.view addSubview:popupObj.view];
[self addChildViewController:popupObj];

您可以将 UIViewController 添加为子视图并设置其框架,使其看起来像弹出窗口。 希望对您有所帮助。

请在您的 rootviewcontroller 上设置导航控制器:

 -(void)viewDidAppear:(BOOL)animated
 {  
      popupObj= [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
      [self.navigationController presentViewController:popupObj animated:YES completion:nil];

  }

或者

  -(void)viewDidAppear:(BOOL)animated
  {  
     popupObj= [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
        [self.view addSubview:popupObj.view];
  }

我有两种方法,可能不太好,但大部分时间都有效。

首先,当第二个视图控制器出现时,显示第一个视图控制器的屏幕截图。像这样:

- (void)setBackGround {
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, [UIScreen mainScreen].scale);
    [self.presentingViewController.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:NO];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.view.layer.contents = (__bridge id)(image.CGImage);
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!_isShown) {
        _isShown = YES;
        [self setBackGround];
    }
}

不要忘记在初始化时设置“_isShown = NO”。

其次:你只能初始化一个视图,然后用动画在视图控制器上显示它。代码在:http://blog.moemiku.com/?p=101

我在博客上更新了一个例子。 Direct download url