2

我有一个带有 2 个视图控制器的单视图应用程序,用于呈现纵向和横向的不同布局。我已经设置了方向更改通知,并且可以在第一次方向更改时成功显示横向视图。

第一个问题:当我将方向更改回纵向时,不显示纵向视图。

第二个问题:当我将方向更改回横向时,横向视图会显示,但我收到警告:

尝试在其视图不在窗口层次结构中的 CalculatorViewController 上呈现 CalculatorViewControllerLandscape。

我浏览了苹果文档和几篇有类似问题的帖子,发现答案在于使用委托,但我无法正确设置委托。这是我的尝试:

CalculatorViewControllerLandscape.h

@protocol SecondControllerDelegate <NSObject>

@end
.....
@property(nonatomic, weak) id <SecondControllerDelegate> delegate;

计算器视图控制器.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;
    }
}

我已经为此工作了几个小时,并检查了所有类似问题的帖子,但我仍然无法弄清楚。提前感谢您的帮助。

4

1 回答 1

1

最佳实践是在一个 中处理旋转事件UIViewController,而不是使用两个单独的事件。我不熟悉界面生成器,但您可以通过编程方式覆盖-(void)viewWillLayoutSubviews;并根据self.interfaceOrientation. 我建议你这样做。

但是,在回答您的问题时:

尝试改变

[[self presentingViewController] dismissViewControllerAnimated:NO completion:nil];

[self dismissViewControllerAnimated:NO completion:nil];

这也可以解决第二个问题,因为旧的横向视图控制器没有被正确关闭。

于 2013-08-29T05:00:01.913 回答