如何先以表单页展示ViewController,再点击按钮切换为全屏?
实现表单页与全屏的切换方案
这个需求我之前做项目时也碰到过,核心思路就是修改ViewController的modalPresentationStyle,再重新触发present逻辑,下面给你一步步拆解实现:
第一步:保存presentedViewController的引用
首先得在当前VC里存好要展示的ViewController(或它的容器控制器)的引用,后面切换时才能精准拿到它。比如在你的VC头文件里加个属性:
@property (nonatomic, strong) UIViewController *presentedSheetVC;
然后修改你现有的present代码:
NewViewController *vc = [[NewViewController alloc] init]; vc.delegate = self; UIViewController *presentViewController; if (IPAD) { // 如果你用了自定义的表单容器(比如你的formSheetControllerWithVC),要拿到容器实例 presentViewController = [self formSheetControllerWithVC:vc]; self.presentedSheetVC = presentViewController; } else { presentViewController = vc; self.presentedSheetVC = vc; } [self presentViewController:presentViewController animated:YES completion:nil];
第二步:实现切换逻辑(两种可选方案)
方案一:直接在NewViewController里处理(简单直接)
给NewViewController里的按钮加点击事件,直接修改自身的modal样式,通过dismiss再present来应用变更:
- (IBAction)toggleFullScreenBtnTapped:(UIButton *)sender { // 切换modal展示样式 if (self.modalPresentationStyle == UIModalPresentationFormSheet) { self.modalPresentationStyle = UIModalPresentationFullScreen; } else { self.modalPresentationStyle = UIModalPresentationFormSheet; } // 先dismiss再重新present,让系统应用新样式 [self dismissViewControllerAnimated:YES completion:^{ [[self presentingViewController] presentViewController:self animated:YES completion:nil]; }]; }
方案二:通过代理让原VC处理(更解耦)
如果想让逻辑分层更清晰,可以用代理通知原VC处理切换:
- 先在NewViewController的头文件定义代理协议:
@protocol NewViewControllerDelegate <NSObject> - (void)newViewControllerDidRequestToggleFullScreen:(NewViewController *)vc; @end @interface NewViewController : UIViewController @property (nonatomic, weak) id<NewViewControllerDelegate> delegate; @end
- 在NewViewController的按钮点击事件里调用代理:
- (IBAction)toggleFullScreenBtnTapped:(UIButton *)sender { if ([self.delegate respondsToSelector:@selector(newViewControllerDidRequestToggleFullScreen:)]) { [self.delegate newViewControllerDidRequestToggleFullScreen:self]; } }
- 在原VC里实现代理方法:
- (void)newViewControllerDidRequestToggleFullScreen:(NewViewController *)vc { // 修改保存的presentedSheetVC的展示样式 if (self.presentedSheetVC.modalPresentationStyle == UIModalPresentationFormSheet) { self.presentedSheetVC.modalPresentationStyle = UIModalPresentationFullScreen; } else { self.presentedSheetVC.modalPresentationStyle = UIModalPresentationFormSheet; } // 重新present使样式生效 [self dismissViewControllerAnimated:YES completion:^{ [self presentViewController:self.presentedSheetVC animated:YES completion:nil]; }]; }
注意事项
- iOS 13及以后,默认的
modalPresentationStyle是UIModalPresentationAutomatic,一定要在present前明确设置为UIModalPresentationFormSheet或UIModalPresentationFullScreen - 如果你的
formSheetControllerWithVC是自定义容器控制器(比如带导航栏的表单页),要确保修改的是容器控制器的modalPresentationStyle,而非内部的NewViewController
内容的提问来源于stack exchange,提问作者SriTeja Chilakamarri
相关产品推荐
相关产品推荐

