Set UICollectionViewCell width programmatically to UICollectionView width

偶尔善良 提交于 2019-12-26 03:47:00

问题


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


来源:https://stackoverflow.com/questions/48948098/set-uicollectionviewcell-width-programmatically-to-uicollectionview-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!