以编程方式设置页面控件但什么也不做

时间:2013-04-17 07:26:08

标签: ios

我正在尝试使用分页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"];

1 个答案:

答案 0 :(得分:2)

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

CGFloat pageWidth = self.collectionView.frame.size.width;
CGPoint scrollTo = CGPointMake(pageWidth * self.index, 0);
[self.collectionView setContentOffset:scrollTo animated:NO];