简体   繁体   中英

UICollectionview and cells

I am using collection view for the first time and I'm not sure how to do something..

I have a UICollectionView with 12 cells. I set the collectView to scroll horizontally only and cells are lined up next to each other. I also turned on paging so I could use UIPageControll to indicate scrolling is active.

I want the collection view to only show four cells on the screen at any time. When the view loads, I get four cells, no problem. However when I scroll horizontally, I get 4 and a half cells. never just four.

Is there a way to tell the collection view only to show four cells at a time?

在此输入图像描述

在此输入图像描述

you can statically add number of cell(items)in collection view,if not require dynamic.

here I am using Scroll Direction Horizontal you can do it same way in vertical. hope this will help

you can do this way also. Just copy this code into your view controller and make some changes.

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

   NSIndexPath *indexPath;
    for (UICollectionViewCell *cell in [self.collectionView visibleCells]) {
        indexPath = [self.collectionView indexPathForCell:cell];
        NSLog(@"%@",indexPath);
    }

    UICollectionViewCell *cell =(UICollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];

    //finally get the rect for the cell
    CGRect cellRect = cell.frame;


    self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, cellRect.origin.y);
}

As Marc said , you could simply control the size of your collection view.

If changing the size is not practical, then you can set content inset on the collection view.

CGFloat cellWidth = … // Cell width
CGFloat collectionViewWidth = … // Collection View Width
CGFloat desiredCollectionViewWidth = cellWidth * 4.0;

CGFloat horizontalInset = collectionViewWidth - desiredCollectionViewWidth;

// To center the collection view
UIEdgeInsets inset = UIEdgeInsetsMake(0, horizontalInset/2, 0, horizontalInset/2);
self.collectionView.contentInset = inset;

// Or, to left justify the collection view
UIEdgeInsets inset = UIEdgeInsetsMake(0, 0, 0, horizontalInset);
self.collectionView.contentInset = inset;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM