在xcode中更改设备方向时,如何加载xib?

Joe*_*Joe 6 cocoa-touch objective-c

当设备的方向改变时,我将如何加载新的xib?即,当设备变为横向时加载横向导向的xib,反之亦然,纵向加载.以及如何自动检测方向变化并从那里进行调整?

Joe*_*Joe 7

显然我要做的就是创建一个基于视图的应用程序将shouldAutoRotateToInterfaceOrientaion设置为YES,并创建两个带有单个xib文件的uiviewcontroller子类,然后将其添加到app视图控制器:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged) name:UIDeviceOrientationDidChangeNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

并将此方法添加到应用程序视图控制器中:

-(void)orientationChanged {
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    if (orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationPortraitUpsideDown) {
        [[NSBundle mainBundle] loadNibNamed:@"Portrait" owner:self options:nil];
    }
    else {
        [[NSBundle mainBundle] loadNibNamed:@"Landscape" owner:self options:nil];
    }

}
Run Code Online (Sandbox Code Playgroud)

就是这样,当设备旋转时,xib自动加载到正确的方向.

编辑:您还需要以编程方式添加两个viewcontrollers(也是@property和@synthesize),以及IB中appviewcontroller.xib中的两个viewcontrollers,每个viewcontrollers的类名对应于您创建的每个xib的viewcontroller子类.然后添加一个视图将它连接到文件的所有者并将IB中的出口连接到您在ib中创建的视图控制器,这应该是全部