Set UICollectionViewCell width programmatically to

2019-03-07 08:57发布

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

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-07 09:36

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)
}
查看更多
三岁会撩人
3楼-- · 2019-03-07 09:52

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);
    }
}
查看更多
登录 后发表回答