2

我正在尝试有一个分页 UICollectionView 并尝试以编程方式设置当前页面,但它什么也不做。它总是从第 0 页开始。

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.minimumLineSpacing = 0;
flowLayout.minimumInteritemSpacing = 0;


// Set up the collection view with no scrollbars, paging enabled
// and the delegate and data source set to this view controller
self.collectionView = [[UICollectionView alloc]
                       initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)
                       collectionViewLayout:flowLayout];

self.collectionView.showsHorizontalScrollIndicator = NO;
self.collectionView.pagingEnabled = YES;
self.collectionView.delegate = self;
self.collectionView.dataSource = self;

[self.view addSubview:self.collectionView];


CGFloat w = self.view.frame.size.width;
CGFloat h = self.view.frame.size.height;

// Set up the page control
CGRect frame = CGRectMake(0, h - 60, w, 60);
self.pageControl = [[UIPageControl alloc]
                    initWithFrame:frame];

// Add a target that will be invoked when the page control is
// changed by tapping on it
[self.pageControl addTarget:self action:@selector(pageControlChanged:)
           forControlEvents:UIControlEventValueChanged];

// Set the number of pages to the number of pages in the paged interface
// and let the height flex so that it sits nicely in its frame
self.pageControl.numberOfPages = self.products.count;
self.pageControl.autoresizingMask = UIViewAutoresizingFlexibleHeight;
self.pageControl.currentPage=self.index;
[self.view addSubview:self.pageControl];
[self.collectionView registerClass:[DetailCustomCell class]
        forCellWithReuseIdentifier:@"CELL_ID"];
4

1 回答 1

2

这是正确的方法,并在 ViewWilLAppear 中进行。

CGFloat pageWidth = self.collectionView.frame.size.width;
CGPoint scrollTo = CGPointMake(pageWidth * self.index, 0);
[self.collectionView setContentOffset:scrollTo animated:NO];
于 2013-04-17T17:50:02.737 回答