当前位置: 动力学知识库 > 问答 > 编程问答 >

iphone - Can you cache UIViewControllers?

问题描述:

I have an application with 8 UIViewControllers presented by navigating from left/right/up/down. They are created on start of the app and kept in an NSArray. Only 1 of them is added to the view tree (addSubview:) at any time - the rest just sit in the cache until they are needed.

Now the problem I am having is when rotating to Landscape. Only the currently visible view changes the bounds.size to Landscape. When navigating to the next view, that view still thinks it is in Portrait (but the containing views will all look in Landscape).

By the way, the view hierarchy of the app is the following: UIWindow -> Main UIViewController -> 1 of the 8 cached UIViewControllers.

For example:

* Change orientation:

- Main UIViewController.view.bounds.size = 480x300 (OK)

- One of the cached UIViewControllers view.bounds.size = 480x300 (OK)

* Go to next view:

- Main UIViewController.view.bounds.size = 480x300 (OK),

- Another of the cached UIViewControllers view.bounds.size = 320x460 (??)

Not sure whats going on. Do I have to tell the cached UIViewControllers somehow that the orientation/size changed or something else?

Thanks a lot

网友答案:

Yes you can. Optimally you should purge the view that each view controller manages when it goes off screen.

Simply assign nil to the view property of the view controller that is being replaced. This will free all resourced used by the view that is not visible anyway. As an added bonus the view is then recreated with proper frame whenever you decide to brin a particular viw controller in front again.

I am also assuming that what you are implementing is a subclass of UIViewController that acts as a container for other view controllers. Like a sibling to UITabController named CWGridController or similar. Noe that it is the responsibility of the the parent view controller (your subclass) to size the frame of it's child view controllers views as needed.

Creating a container view controller is not a small task, and the support for doing it is not complete from Apple. There are a few things you must do including but not limited to:

  • Forward all orientation change calls to all child view controllers.
  • Properly call all appear/disappear on child view controller as needed.

The last part to make it work is to break some rules. View controllers works very badly unless they know about their parent view controller, layout will be wrong and modal view controller behaves strange. Unfortunately the parentViewController is readonly, or so you would think. Setting it anyway using KVC will solve most problems, and Apple does not seem to object when you submit to App Store:

[childViewController setValue:self forKey:@"parentViewController"];
网友答案:

In viewWillAppear you will have to check the interface orientation and set the frames accordingly.

分享给朋友:
您可能感兴趣的文章:
随机阅读: