我是UIPageViewControllers的新手。我已经设置了一个可以分页通过不同类型的UIViewControllers。
我注意到当我滚动回到前一个时,所有数据和状态都被重置(即我之前更改了UIViewController背景颜色,并且它已重置为默认值)。我正在使用故事板中的恢复ID来启动这些控制器。
如果我使用这些不应该保存控制器的状态?
更换控制器的代码:
#pragma mark - UIPageViewControllerDataSource
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
//This is nice and avoids having to use a counter
NSString *vcRestorationID = viewController.restorationIdentifier;
NSUInteger index = [self.controllerRestorationIDs indexOfObject:vcRestorationID];
if (index == 0) {
return nil;
}
return [self viewControllerAtIndex:index - 1];
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
NSString *vcRestorationID = viewController.restorationIdentifier;
NSUInteger index = [self.controllerRestorationIDs indexOfObject:vcRestorationID];
//Don't allow it to go forward if there is one at the end
if (index == self.controllerRestorationIDs.count - 1) {
return nil;
}
return [self viewControllerAtIndex:index + 1];
}
#pragma mark - Private Methods
- (UIViewController *)viewControllerAtIndex:(NSUInteger)index
{
// Only process a valid index request.
if (index >= self.controllerRestorationIDs.count) {
return nil;
}
// Create a new view controller.
BaseContentViewController *contentViewController = (BaseContentViewController *)[self.storyboard instantiateViewControllerWithIdentifier:self.controllerRestorationIDs[index]];
// Set any data needed by the VC here
contentViewController.rootViewController = self;
return contentViewController;
}
有没有办法这样做,所以保存状态并且每次都不重新加载控制器?
答案 0 :(得分:1)
发生此行为是因为每次访问时都会实例化一个新的视图控制器。
解决这个问题:
第一个解决方案是volatile:只要取消分配pageVC,您就会丢失对视图控制器所做的修改。第二个更确定。