开发者

How to support both portrait and landscape orientations with xib files?

I'm interested in having a UIViewController that supports all orientations and cleanly uses two xib files to set up its subviews.

One possibility seems to be to use NSBundle's loadNibNamed: method to load a new view hierarchy at each rotation, but this seems inefficient, and could have unfor开发者_JAVA技巧tunate side effects. For example, after reloading from a nib file, all my views would lose their previous state, such as adding text to a text field, etc.

Is there a better way to do this?


After some more research, I was not able to find an elegant solution to this. Because re-loading elements from a xib file at each rotation seemed slow and eliminated any dynamic view-based data, I switched over to a code-based setup (i.e. no more xib files).

I decided to create a method like this:

// This is for an iPad root-level view controller.
- (void)setupForOrientation:(UIInterfaceOrientation)orientation {
  if (UIInterfaceOrientationIsPortrait(orientation)) {
    CGRect bounds = CGRectMake(0, 0, 768, 1004);
    bkgImageView.frame = bounds;
    // Other view positioning for portrait.
  } else {
    CGRect bounds = CGRectMake(0, 0, 1024, 748);
    bkgImageView.frame = bounds;
    // Other view positioning for landscape.
  }
  [self drawBackgroundForOrientation:orientation];
}

This method is called from the shouldAutorotateToInterfaceOrientation: method, and handed the new orientation.


Instead of calling your function from shouldAutorotateToInterfaceOrientation, where you just need to say YES or NO, you should really do your stuff in delegate functions like willRotateToInterfaceOrientation which is meant to do things like what you are doing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜