-->

UICollectionView Vertical Paging With Code In Obje

2019-08-16 18:50发布

问题:

I have a ViewController mycollectionview and create a UICollectionView collection view in it and set size to the frame size. I have a Custom UICollectionViewCell CollectionViewCell class. Images sizes are different and I want to just show a one cell and full fitted to screen at the same time (when not scrolling). Here is mycollectionview code :

- (void)viewDidLoad
{
    [super viewDidLoad];
    imgnum = @[@"1.jpg",@"2.jpg",@"3.jpeg",@"4.jpg"];
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    layout.itemSize = CGSizeMake(80.0, 80.0);
    collectionview = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    collectionview.translatesAutoresizingMaskIntoConstraints = NO;
    collectionview.delegate = self;
    collectionview.dataSource = self;
    collectionview.bounces = false;
    [collectionview registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    [self.view addSubview:collectionview];
{

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionview dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.pic.image = [UIImage imageNamed:imgnum[indexPath.row%4]];
    cell.lab.text = @"Eiffel";
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    float w = self.view.frame.size.width;
    CGSize a = [UIImage imageNamed:imgnum[indexPath.row%4]].size;
    float aspect = a.width/a.height;
    return CGSizeMake(w, w * 1/aspect);
}

And it's my CollectionViewCell code :

- (void)initialize
{
    _pic = [UIImageView new];
    _pic.translatesAutoresizingMaskIntoConstraints=false;
    [self.contentView addSubview:_pic];
    _lab = [UILabel new];
    _lab.textColor = [UIColor blackColor];
    _lab.translatesAutoresizingMaskIntoConstraints = false;
    [self.contentView addSubview:_lab];
}

回答1:

I would recommned you not to use this CGSize a = [UIImage imageNamed:imgnum[indexPath.row%4]].size; as your image size if more than the device frame height it will create a problem and expand the cell to become scrollable.

  1. You want to show one image at a time so I would say set the contentcell height same as the frame of device height or collectionview.
  2. Later set the UIImageview setContentMode : AspectFit so image is fitted in one cell and your scroll for one image at time can work.

Check my example that I created for you, hope it helps.http://www.filedropper.com/collectionviewperpageex