Set UICollectionViewCell width programmatically to

2019-03-07 09:18发布

问题:

In the collection view how do we set the cell size of width and height based on the overall collection view. it will set for small to large devices (for example : if the collection view overall width = 375.0000 and we divide into 3. so it will set for the all the large and small devices).

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"SETTING SIZE FOR ITEM AT INDEX %d", (int)indexPath.row);
    CGSize mElementSize = CGSizeMake(125, 125);
    return mElementSize;
}

回答1:

For Phone and Tablet(Set for all the screens)

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
    {
        return CGSizeMake(self.view.frame.size.width/3, 125);

    }
    else
    {
        NSLog(@"width %f",self.view.frame.size.width);
        return CGSizeMake(self.view.frame.size.width/3, 150);
    }
}


回答2:

Set UICollectionViewDelegateFlowLayout method in your code

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{ 
    return CGSize(width:(collectionView.bounds.size.width/numberOfCellInRow), height:270)
} 

And also add this two line in your cell's awakeFromNib() method for update your cell's constraint according to cell size.

override func awakeFromNib()
{ 
    self.contentView.autoresizingMask.insert(.flexibleHeight)
    self.contentView.autoresizingMask.insert(.flexibleWidth)
}