简体   繁体   中英

Unable to resize UIImageView into UICollectionViewCell

In an iOS app, I have a UICollectionView that displays a grid of pictures. However I am unable to precisely set the size of the UIImageView which is contained in each UICollectionViewCell. All are defined in Interface Builder.

As we can see in the image below, not only the size of each pictures is not the same (code shows it should be fixed for all), but they are not matching my setFrame values. Tried to apply recommendations of other posts, but issue stays the same.

How to be able to set fixed size for UIImageView's ?

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"backgroundCell" forIndexPath:indexPath];

    UIImageView *imageView = (UIImageView *)[cell viewWithTag:110];
    imageView.image=[UIImage imageNamed:[allImages objectAtIndex:indexPath.row]];
    imageView.translatesAutoresizingMaskIntoConstraints=YES;
    imageView.frame=CGRectMake(10,10, 50, 200);
    cell.backgroundColor=[UIColor redColor];
    return cell;
}

在此处输入图片说明

EDIT 1:

Though below provided auto layout constraints will work fine, noticed that imageView is added as a part of cell's xib so rather than adding constraints manually/programmatically make sure you apply the same constraints in xib

Try setting auto layout constraint as shown below

    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.leftAnchor.constraint(equalTo: cell.leftAnchor).isActive = true
    imageView.rightAnchor.constraint(equalTo: cell.rightAnchor).isActive = true
    imageView.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
    imageView.bottomAnchor.constraint(equalTo: cell.bottomAnchor).isActive = true

Finally, try modifying the content mode of your image view

imageView.contentMode = .scaleAspectFit/.scaleAspectFill depending on your need :)

Hope it helps

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