用年份和月份填充 UICollectionViewCell

Populate UICollectionViewCell with Years and Months

我需要用从 20002050 的年份列表填充 UICollectionView 的单元格。

每个单元格必须包含一年中的一个月到第十二个月,然后从新的一年开始。

例如 2000 年的 12 个单元格,2001 年的另外 12 个单元格等...

使用 swift 5 的最佳方式是什么?

您可以将单元格计数设置为 (2050-2000)*12

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (2050-2000)*12
}

然后定义开始年份变量和月份名称数组

var year:Int = 2000
let months:[String] = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]

现在您可以将数据添加到集合视图单元格

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //define cell

    cell.lblYear.text = "\(year+indexPath.row.quotientAndRemainder(dividingBy: 12).quotient)"
    cell.lblMonth.text = months[indexPath.row % 12]



    return cell
}