【问题标题】:Why is array in collection view getting multiplied by amount of sections?为什么集合视图中的数组乘以部分数量?
【发布时间】:2019-12-23 05:42:04
【问题描述】:

当我想在集合视图中快速查看一个数组时,它会乘以集合视图中的部分数量。为什么会这样,我该如何阻止它?

let numbers = ["one", "two", "three"]

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3;
    }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let theCell = collectionView.dequeueReusableCell(withReuseIdentifier: "theCell", for: indexPath) as! cell

for number in numbers {
            print("\(number)")
        }

return theCell

}

我希望它会回来:

一个

两个

三个

但它却返回了:

一个

两个

三个

一个

两个

三个

一个

两个

三个

【问题讨论】:

    标签: ios arrays swift uicollectionview


    【解决方案1】:

    由于每个部分有三个单元格,并且假设您只有一个部分,collectionView(_:cellForItemAt:) 会被调用 3 次。每次打印numbers 数组的所有元素时。要仅打印与当前索引对应的元素,请将 for 循环替换为:

    print(numbers[indexPath.row])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多