简体   繁体   中英

Set UICollectionViewCell width programmatically to UICollectionView width

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;
}

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)
}

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);
    }
}

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