在iOS中以编程方式显示另一个UIViewController作为弹出窗口?
在iOS中以编程方式显示另一个UIViewController作为弹出窗口?
我有一个主仪表板(`UITableViewController`),一旦我登录,我需要显示这个页面并显示一个欢迎消息,我使用`UIViewController`来显示。
我该如何在我的`ViewDidAppear()`方法中显示这个弹出窗口?
我正在使用以下代码,但它不起作用:
-(void)viewDidAppear:(BOOL)animated{ popupObj= [self.storyboard instantiateViewControllerWithIdentifier:@"popup"]; [popupObj setModalPresentationStyle:UIModalPresentationCurrentContext]; }
请帮帮我..
我看到了一些stackoverflow的链接
更新
当我将代码更改为以下代码时:
-(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)`。
显示另一个UIViewController作为弹出窗口在iOS中的问题出现的原因是,尽管代码创建了视图控制器并设置了其呈现样式,但实际上并没有将其呈现出来。为了实现呈现,需要在现有的两行代码之后添加以下代码行:
[self presentViewController:popupObj animated:true completion:nil];
解决方法就是添加上述代码行,将弹出窗口的视图控制器呈现出来。这将使用`presentViewController`方法将`popupObj`视图控制器作为弹出窗口以动画方式呈现在当前的视图控制器中。其中,`animated`参数指定是否使用动画效果呈现,`completion`参数用于指定呈现完成后要执行的操作,这里设置为`nil`表示不执行任何操作。
通过添加上述代码行,问题将得到解决,即可以实现以编程方式显示另一个UIViewController作为弹出窗口的效果。
问题的出现原因是在iOS中如何以弹出窗口的形式展示另一个UIViewController。解决方法有两种。
第一种方法是在第二个视图控制器出现时,显示一个第一个视图控制器的屏幕截图作为背景。具体代码如下:
- (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"。
第二种方法是只初始化一个视图,并以动画方式展示在一个视图控制器上。相关代码可以在这篇博客中找到,也可以直接下载示例代码。
下面是示例代码的效果图:
在iOS中,有时候我们希望以弹出窗口的形式展示另一个UIViewController。一个常用的方法是将另一个UIViewController作为当前UIViewController的子视图,并设置其frame属性来实现弹出窗口的效果。
具体操作如下:
首先,我们需要实例化需要展示的UIViewController,可以使用storyboard的instantiateViewControllerWithIdentifier方法来实例化。
popupObj= [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
接下来,我们可以设置弹出窗口的位置和大小,通过设置popupObj.view的frame属性来实现。
popupObj.view.frame = CGRectMake(20, 200, 280, 168);
然后,我们将弹出窗口的视图添加到当前UIViewController的视图中。
[self.view addSubview:popupObj.view];
最后,我们需要将弹出窗口的UIViewController添加为当前UIViewController的子视图控制器。
[self addChildViewController:popupObj];
这样,我们就成功地将另一个UIViewController以弹出窗口的形式展示出来了。
希望这对你有帮助。
这样应该是可以的,改变frame属性不仅可以改变弹出窗口的位置和大小,而且还可以改变其x、y坐标以及宽度和高度。