禁用焦点触发的UICollectionView滚动

时间:2015-11-04 14:01:52

标签: uicollectionview tvos apple-tv

当单元格被聚焦时,有没有办法禁用UICollectionView的自动滚动?我想在聚焦时手动调整单元格的内容偏移量。

我不想更新内容偏移量:

- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context
       withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
    [coordinator addCoordinatedAnimations:^
     {
         [UIView animateWithDuration:[UIView inheritedAnimationDuration]
                          animations:^
          {
              // Move next focused cell.
              if ([context.nextFocusedView isKindOfClass:[YBZEventCollectionViewCell class]])
              {
                  UICollectionViewCell *cell = (UICollectionViewCell *)context.nextFocusedView;

                  CGPoint offset = CGPointMake(CGRectGetMinX(cell.frame), 0.0f);

                  [_collectionView setContentOffset:offset];
              }
          }];

     } completion:nil];
}

这样可行,但由于焦点引擎也会移动我的单元格(滚动它),我最终得到的动画不是很平滑,有一个"踢"在它的最后。

3 个答案:

答案 0 :(得分:2)

刚遇到这个问题。要在焦点更改时禁用UICollectionView的自动滚动,只需在界面构建器中的集合视图的“Scroll View”属性中禁用滚动:

enter image description here

答案 1 :(得分:-1)

我不知道“自动滚动”是什么意思,但是要更改集合视图单元格,您可以在自定义单元格类中使用 didUpdateFocusInContext

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    coordinator.addCoordinatedAnimations({ [unowned self] in
        if self.focused {
            self.titleTopConstraint.constant = 27

            self.titleLabel.textColor = UIColor.whiteColor()
        } else {
            self.titleTopConstraint.constant = 5

            self.titleLabel.textColor = UIColor(red: 100 / 255, green: 100 / 255, blue: 100 / 255, alpha: 1)
        }
        self.layoutIfNeeded()
    }, completion: nil)
}

或者,如果您没有自定义单元格,请使用UICollectionViewDelegate中的 didUpdateFocusInContext

func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    coordinator.addCoordinatedAnimations({ () -> Void in
        if let indexPath = context.nextFocusedIndexPath, let cell = collectionView.cellForItemAtIndexPath(indexPath) {
            // the cell that is going to be focused
        }
        if let indexPath = context.previouslyFocusedIndexPath, let cell = collectionView.cellForItemAtIndexPath(indexPath) {
            // the cell that is going to be unfocused
        }
    }, completion: nil)
}

答案 2 :(得分:-1)

UICollectionView子类UIScrollView开始,集合视图委托可以实现滚动视图委托方法。你可能想要的是:

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                 withVelocity:(CGPoint)velocity
          targetContentOffset:(inout CGPoint *)targetContentOffset

默认情况下,targetContentOffset将是UIKit滚动到的滚动偏移量,但是如果你更改了值,那么UIKit将在那里滚动。

如果你真的真的不希望UIKit为你做任何自动滚动,你总是可以通过将scrollEnabled设置为NO来完全禁用滚动。