当视图当前不可见时,更改集合视图的滚动位置

时间:2015-11-16 14:33:56

标签: ios uiscrollview uicollectionview

有两种情况我在设置集合视图的滚动位置时遇到问题:

  • 启动时我想滚动到某个项目(起始位置!=集合视图的开头)
  • 视图目前尚未显示,但在“背景”中,集合视图应滚动到某个项目

将集合视图滚动到某个单元格的可靠方法是什么?目前我在scrollToItemAtIndexPath设置了viewDidAppear的滚动位置,但这对我来说太晚了。

2 个答案:

答案 0 :(得分:2)

尝试在viewWillAppear/DidAppear中调用moethod:

像你这样的Loooks无法在UICollectionViewScrollPositionLeft !!!!

中滚动到项目

你可以根据你的收藏视图滚动方向修改-(void)viewDidLayoutSubviews{ [super viewDidLayoutSubviews]; NSIndexPath *indexPath=[NSIndexPath indexPathForItem:3 inSection:0]; //indexpath for the item to scroll [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES]; }

    func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    var indexPath: NSIndexPath = NSIndexPath.indexPathForItem(3, inSection: 0)
    collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
}    

<强>夫特:

viewDidLayoutSubviews

方法viewWillAppear只会调用一次,并且不会根据集合视图滚动调用它!

通常会在viewDidAppear之后和public class ImageGridAdapter extends BaseAdapter { public Uri imageUri; private Context mContext; public ImageGridAdapter(Context c) { this.mContext = c; } @Override public int getCount() { return 5; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { imageUri = PictureGroupActivity.selectedImage; ImageView imageView; if (convertView == null) { imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageURI(null); imageView.setImageURI(imageUri); return imageView; } } 之前调用它!

答案 1 :(得分:0)

试试这个:

CGPoint newContentOffset = yourCollectionView.contentOffset;
float offset = selectedIndex * (self.view.bounds.size.width + cellSpacing);
newContentOffset.x += offset;
yourCollectionView.contentOffset = newContentOffset;
相关问题