【问题标题】:Change only width of collectionviewcell仅更改 uicollectionviewcell 的宽度
【发布时间】:2014-10-15 18:09:43
【问题描述】:

我正在尝试使用根据屏幕大小改变宽度的单元格创建一个集合视图。在 iOS 和 swift 中。目前我正在使用函数“sizeForItemAtIndexPath”。我不能只输入高度,因为我在情节提要中有不同类型的单元格具有不同的高度。所以我希望高度相同但能够改变宽度

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSizeMake(changingWidth, sameHeight)
}

【问题讨论】:

  • 您是否在屏幕尺寸更改时重新加载您的收藏视图?
  • 是的,不是问题。问题是要获得单元格的高度,所以我可以返回它。这是因为我有许多不同的原型单元,或者不管它们叫什么,你在情节提要中制作的那些。这些细胞有不同的高度。所以我不能只在“相同高度”中写 170

标签: ios swift collectionview


【解决方案1】:

斯威夫特

我试过了,它对我有用:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    var height:CGFloat = 10.0  // Fallback value
    if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        height = layout.itemSize.height
    }
    return CGSize(width: collectionView.frame.width, height: height)
}

【讨论】:

    【解决方案2】:

    这是我的第一次尝试,但我不知道调用的顺序——这可能会设置无限递归或以其他方式破坏你的东西:

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
            return CGSizeMake(changingWidth, cell.frame.height)
        } else {
            return CGSizeMake(changingWidth, defaultHeight)
        }
    } 
    

    【讨论】:

    • 它不起作用。似乎 sizeForItemAtIndexPath 在 cellForItemAtIndexPath 之前运行,所以 cellForItemAtIndexPath 将始终为零。如果我更新它,单元格高度将是默认高度。
    • 这就是我害怕的。德拉特!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多