【问题标题】:How to center a cell in UICollectionView?如何在 UICollectionView 中将单元格居中?
【发布时间】:2017-12-06 04:53:57
【问题描述】:

我有一个 UICollectionView,它包含从一月到十二月的 12 个单元格,如下面的屏幕截图所示:

如何使当前月份始终位于集合视图的中心?例如,Dec 应显示在本月的中心。

其中一个解决方案是自动滚动到下一页并将第 12 个单元格居中,但我该如何实现呢?

【问题讨论】:

标签: ios objective-c uicollectionview


【解决方案1】:

您可以使用cellForItem 函数定义单元格的显示方式,并使用 UICollectionView 函数reloadData() 随时更新您认为有必要的所有单元格。

如果 12 月应该是中间的单元格,请确保 5 或 6 个单元格在 12 月之前出现,您应该能够通过 cellForItem 中的简单条件做到这一点。

例如,由于您有 12 个单元格,您可以获取当前月份为整数(12 月为 12),您将知道第一个月将是 12 - 6 = 6(六月),因此您可以此计算适用于每个 indexPath。

为了简化您的工作:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = ...
    let month = GetCurrentMonthAsInteger()
    var cellMonth = month - 6 + indexPath.row //or section if you have 12 sections
    if(cellMonth < 1) {cellMonth = 12 + cellMonth}
    else if(cellMonth > 12) {cellMonth = cellMonth - 12}
    cell.setInformationForMonth(cellMonth)
    ...
    return cell
}

【讨论】:

    【解决方案2】:

    您可以尝试将单元格和线条的最小间距设为零

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 2013-06-14
      相关资源
      最近更新 更多