在iOS中定位时加载另一个.xib

时间:2013-12-21 17:04:12

标签: ios objective-c

我使用下面的代码来实现它,但它不起作用。请给我一些建议。非常感谢。

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(orientationChanged:)  name:UIDeviceOrientationDidChangeNotification  object:nil];

}

orientationChanged()函数:

  - (void)orientationChanged:(NSNotification *)notification{
        [self adjustViewsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
    }

adjustViewsForOrientation()函数:

- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation {

    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        NSLog(@"load portrait view");
        [[NSBundle mainBundle] loadNibNamed:@"DashBoardViewController" owner:self options:nil];
    }
    else if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight)
    {
        NSLog(@"load landscapeview");
        [[NSBundle mainBundle] loadNibNamed:@"DashBoardLandscapeView" owner:self options:nil];
    }
}

运行时,它始终显示DashBoardViewController.xib。在lanscape中,它仍然显示DashBoardViewController.xib。我不知道为什么。

2 个答案:

答案 0 :(得分:1)

这是因为您实际上没有设置视图。

您需要执行以下操作:

self.view = [[NSBundle mainBundle] loadNibNamed:@"DashBoardLandscapeView" owner:self options:nil] objectAtIndex:0];

这将从Xib文件加载视图,并将当前视图设置为该视图。

不要忘记在代码中看到添加objectAtIndex:0。

答案 1 :(得分:0)

使用willRotateToInterfaceOrientation:方法而不是通知

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if( UIInterfaceOrientationIsLandscape(toInterfaceOrientation) )
    {
        NSLog(@"load landscapeview");
        [[NSBundle mainBundle] loadNibNamed:@"DashBoardLandscapeView" owner:self options:nil];
        //[self viewDidLoad];
    }
    else
    {
        NSLog(@"load portrait view");
        [[NSBundle mainBundle] loadNibNamed:@"DashBoardViewController" owner:self options:nil];
        //[self viewDidLoad];
    }
}

如果你有逻辑逻辑,也许你必须取消注释[self viewDidLoad]