简体   繁体   中英

how to have one view controller for multiple nib files iphone

So i've been the whole morning trying to figure out how to load a second nib file from one view controller on orientation change but i didn't succeed and that's why i come here and ask for help. The thing is that i want to load a landscape nib file when the device is rotated. I have this code so far it doesn't work:

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation==UIInterfaceOrientationLandscapeRight || toInterfaceOrientation==UIInterfaceOrientationLandscapeLeft) {
        [self initWithNibName:@"myNibFile" bundle:nil];
    }
}

The new nib is not being loaded. In interface builder i have the file owner being set to this view controller so it should work. I also tried with: [[NSBundle mainBundle] loadNibNamed:@"myNibFile" owner:self options:nil]; but i had no luck either Can you provide an example on how to load a nib file from initWithNibName or a useful link? I don't seem to find it on the web.

Thanks a lot.

For this you have create new instance of your class.You can not change nib of view controller at run time.

Why are you creating multiple nib files for one view controller. Just create multiple views in single nib file and user accordingly.

Changing the nib of a controller at runtime is not a good idea at all (not sure if it is even possible legally ). It can lead to nibs dangling in memory & eventual memory leaks. I encountered the same problem some time back & found that not using IB & nibs is the easiest way to go (luckily my view wasn't very complicated).

The solution was to layout the subcomponents in code & adjust them in accordance with an orientation change. I did the following in my UIViewController subclass-

-(void) adjustLayout:(UIInterfaceOrientation)orientation
{
    if(UIInterfaceOrientationIsPortrait(orientation))
    {
         mySubview1.frame = frameInAccordanceWithPortrait;
    }
    else
    {
        mySubview1.frame = frameInAccordanceWithPortrait;
     }
}

- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self adjustLayout:toInterfaceOrientation];
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM