以编程方式将UICollectionViewCell宽度设置为UICollectionView宽度

问题描述 投票:-2回答:2

在集合视图中,我们如何根据整个集合视图设置宽度和高度的单元格大小。它将为小型到大型设备设置(例如:如果集合视图总宽度= 375.0000,我们将其分为3.因此它将为所有大型和小型设备设置)。

- (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;
}
ios objective-c uicollectionview uicollectionviewcell
2个回答
0
投票

适用于手机和平板电脑(适用于所有屏幕)

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

0
投票

在代码中设置UICollectionViewDelegateFlowLayout方法

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

并且还在单元格的awakeFromNib()方法中添加这两行,以根据单元格大小更新单元格的约束。

override func awakeFromNib()
{ 
    self.contentView.autoresizingMask.insert(.flexibleHeight)
    self.contentView.autoresizingMask.insert(.flexibleWidth)
}
© www.soinside.com 2019 - 2024. All rights reserved.