我有一个带有2个视图控制器的视图应用程序,可以为纵向和横向呈现不同的布局。我已设置方向更改通知,并可在第一个方向更改时成功显示横向视图。
第一个问题: 当我将方向改回纵向时,不显示纵向视图。
第二个问题: 当我将方向改回横向时,会显示横向视图,但我收到警告:
尝试在其视图不在窗口层次结构中的CalculatorViewController上显示CalculatorViewControllerLandscape。
我已经浏览了苹果文档和几个有类似问题的帖子,并且已经发现答案在于使用委托但我无法正确设置委派。这是我的尝试:
CalculatorViewControllerLandscape.h
@protocol SecondControllerDelegate <NSObject>
@end
.....
@property(nonatomic, weak) id <SecondControllerDelegate> delegate;
CalculatorViewController.h
@interface CalculatorViewController : UIViewController <SecondControllerDelegate> {
....
}
@property (strong) CalculatorViewControllerLandscape *landscapeVC;
CalculatorViewCalculator.m
- (void)awakeFromNib
{
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
// register as a delegate
self.navigationController.delegate = (id)self;
}
- (void)orientationChanged:(NSNotification *)notification
{
UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
if (UIDeviceOrientationIsLandscape(deviceOrientation) &&
!isShowingLandscapeView)
{
NSLog(@"Orientation has changed to landscape");
// code here to show landscape storyboard
UIStoryboard *landscapeStoryboard = [UIStoryboard storyboardWithName:@"LandscapeStoryboard" bundle:nil];
UIViewController *landscapeViewController = [landscapeStoryboard instantiateInitialViewController];
[self presentViewController:landscapeViewController animated:YES completion:nil];
isShowingLandscapeView = YES;
}
else if (UIDeviceOrientationIsPortrait(deviceOrientation) &&
isShowingLandscapeView)
{
NSLog(@"Orientation has changed to portrait");
[[self presentingViewController] dismissViewControllerAnimated:NO completion:nil];
isShowingLandscapeView = NO;
}
}
我一直在研究这个问题好几个小时,并检查了所有类似问题的帖子,但我仍然无法弄清楚。在此先感谢您的帮助。
答案 0 :(得分:1)
最佳做法是在单个UIViewController
中处理轮换事件,而不是使用两个单独的轮换事件。我不熟悉界面构建器,但是通过编程,您可以覆盖-(void)viewWillLayoutSubviews;
并根据self.interfaceOrientation
适当地布局您的视图。我建议你这样做。
然而,在回答你的问题时:
尝试更改
[[self presentingViewController] dismissViewControllerAnimated:NO completion:nil];
到
[self dismissViewControllerAnimated:NO completion:nil];
这也可以解决第二个问题,因为旧的横向视图控制器没有被正确解除。