在iPhone 5屏幕上的CollectionViewCell

时间:2017-02-16 11:23:55

标签: swift uicollectionviewcell

我有这个自定义的UICollectionViewCell,它在iphone 7上工作得很好,但是当我在Iphone 5模拟器上运行时,事情很奇怪。 我的集合视图包含许多部分,每个部分有一个项目。它看起来像一个表格视图,这意味着每个单元格都是全宽度,并且它们都像在表视图中一样在彼此之上。 出于某种原因,在Iphone 5中,帧为:( - 27.5,50.0,320.0,45.7143) 这意味着它具有正确的宽度和高度,但它在屏幕左侧开始27.5点。我像这样更新单元格:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> ProfileCollectionCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ProfileCollectionCell
    let width = CGFloat((self.collectionView?.frame.width)!)
    let height = width/7
    cell.frame.size = CGSize(width: width, height: height)
    return cell
}

我怎样才能正确定位框架?

2 个答案:

答案 0 :(得分:3)

您不应在cellForItemAtIndexPath

中设置单元格的框架

相反,实施UICollectionViewDelegateFlowLayout方法......

func collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) {
    let width = collectionView?.frame.width ?? 0
    let height = width / 7
    return CGSize(width: width, height: height)
}

答案 1 :(得分:1)

首先将协议添加到您的班级UICollectionViewDelegateFlowLayout并添加以下代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
   let width = CGFloat((self.collectionView?.frame.width)!)
   let height = width/7
   return CGSize(width: width, height: height)
}
相关问题