从呈现的视图控制器返回时保留UICollectionView contentOffset

时间:2014-07-18 15:31:17

标签: ios uiscrollview uicollectionview contentoffset

我有一个包含UICollectionView的UIViewController子类。选择单元格会显示一个新的视图控制器。当我返回第一个视图控制器时,集合视图的contentOffset被重置为CGPointZero。

从我的研究来看,这似乎是标准行为。

我可以通过向我的视图控制器子类添加私有属性来重置contentOffset,在viewWillDissapear方法中保存contentOffset并在viewWillAppear方法的集合视图中重置它。

我想知道,是否有另一种方法可以防止滚动视图内容偏移被重置(不需要额外的属性)?

我的目标是iOS7。

第二个视图控制器如下所示:

[self presentViewController:secondVC animated:YES completion:nil];

并且这样解雇(在第二视图控制器中):

-(void) dismiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

编辑:经过进一步调查后,显示重置contentOffset不是默认行为。我还没弄清楚为什么它在我的应用程序中发生了。我正如上面的代码所示,正在展示。

3 个答案:

答案 0 :(得分:0)

有两种选择。如果你的应用程序使用UINavigationController,它应该保留最后访问的单元格,不确定你是如何使用的。如果没有,您可以随时创建通知,并在您返回上一个屏幕的那一刻,发送UICollectionView的更新或您拥有的任何内容并滚动到正确的位置。 请记住,UIViewController生命周期以及在更新用户界面之前它将如何出现。

答案 1 :(得分:0)

您可以在AppDelegate中创建CGPoint对象。然后,您可以在存在时将该值设置为CollectionView对象contentOffset,并将其解除;

[self presentViewController:secondVC animated:YES completion:{
    appDelegate.tempContentValue = _collectionView.contentOffset;
}];

[self dismissViewControllerAnimated:YES completion:{
    UIViewController *first = [UIViewController alloc] init];
    [first.collectionView setContentOffset:appDelegate.tempContentValue animated:YES];
}];

答案 2 :(得分:0)

   @property (nonatomic,assign) CGPoint newContentOffset;

然后当您导航到另一个视图/显示另一个视图

  self.newContentOffset = self.collectionView.contentOffset;

在viewWillAppear

  [self.collectionView reloadData];

   if (self.newContentOffset) {
        [self performSelector:@selector(setContentOffset) withObject:nil afterDelay:0.1];
   }


  -(void)setContentOffset {
        [self.collectionView setContentOffset:self.newContentOffset];

   }

申请时会有一个小混蛋。但如果可以,你可以继续这个方法