如何在CollectionView中添加业务逻辑?

时间:2019-05-15 09:55:35

标签: ios swift uicollectionview

业务逻辑是:-

  1. 如果项目是偶数,则在每行中显示2。
  2. 如果项目为奇数,则显示第一个跨整个行,并在每行显示其余的跨度2。

1 个答案:

答案 0 :(得分:2)

sizeForItemAt方法检查items.count,如果它是第一行且项目计数为奇数,则返回collectionView.bounds.width。其他返回collectionView.bounds.width / 2

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if items.count % 2 == 1 && indexPath == IndexPath(item: 0, section: 0) {
        return CGSize(width: collectionView.bounds.width, height: 50)
    } else {
        return CGSize(width: (collectionView.bounds.width / 2) - 10, height: 50)
    }
}

奇数

enter image description here

甚至

enter image description here

相关问题