【问题标题】:Set UICollectionViewCell width programmatically to UICollectionView width以编程方式将 UICollectionViewCell 宽度设置为 UICollectionView 宽度
【发布时间】:2018-02-23 12:37:19
【问题描述】:

在集合视图中,我们如何根据整体集合视图设置单元格的宽度和高度。它将为小型到大型设备设置(例如:如果集合视图总宽度 = 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


【解决方案1】:

在代码中设置 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)
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      相关资源
      最近更新 更多