UICollectionView cell size ContentView Issue

2019-09-03 09:17发布

问题:

I have a UICollectionViewCell in storyboard the cell. The cell size is 45 for first 6 cells and 50 for the last cell.

Storyboard cell size has width = 60.

The following issue occurs when running on iOS Simulator 4s.

If you see the cell at location 2,4,6 there is a red background of UICollectionView.

I get the following in layoutSubView of the subclass.

Frame = {{0, 0}, {50, 60}}
Frame = {{0, 0}, {45, 60}}
Frame = {{0, 0}, {45, 60}}
Frame = {{0, 0}, {45, 60}}
Frame = {{0, 0}, {45, 60}}
Frame = {{0, 0}, {45, 60}}
Frame = {{0, 0}, {45, 60}}


- (void)layoutSubviews
{
    [super layoutSubviews];

    NSLog(@"Frame = %@",NSStringFromCGRect(self.bounds));
    self.contentView.frame = self.bounds;
}

Also, added the resizing in awakefromnib which did not work.

-(void)awakeFromNib{
    [super awakeFromNib];

   self.contentView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin |UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth ;
}

The above result which is printed is correct, the sizes are perfect.

Adding the following in ViewController also did not work

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.0;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0.0;
}

A demo project is available for some time at url.

On further investigation I found was because of scaling simulator. The screens are with a 4s simulator. I don't know if on device it will cause any issue.

100% => result Ok 75% => red background lines appear 50% => result Ok 33% => result Ok 25% => red background lines appear

回答1:

try to set the constraints of the collectionView like this