一个UICollectionView Xcode中的两个单元格



[我想在一个UICollectionView中使用两个自定义单元格,到目前为止我一直在尝试,但我被卡住了。第一行和第二行的单元格一,第二行单元格二,第三行单元格一,你明白了。

这是代码


import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var CV: UICollectionView!

let labelArray = ["one", "two", "three", "four"]
let imageArray = [UIImage(named: "one"), UIImage(named: "two"), UIImage(named: "three"), UIImage(named: "four") ]
override func viewDidLoad() {
super.viewDidLoad()
CV.delegate = self
CV.dataSource = self
CV.reloadData()

//        let nibCellOne = UINib(nibName: "CVCellOne", bundle: nil)
//        let nibCellTwo = UINib(nibName: "CVCellTwo", bundle: nil)
//        CV.register(nibCellOne, forCellWithReuseIdentifier: "CVCellOne")
//        CV.register(nibCellTwo, forCellWithReuseIdentifier: "CVCellTwo")
CV.register(CollectionViewCell.self, forCellWithReuseIdentifier: "CVCellOne")
CV.register(CollectionViewCell.self, forCellWithReuseIdentifier: "CVCellTwo")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCellOne", for: indexPath) as! CollectionViewCell
cell1.cellOneLabel.text = labelArray[indexPath.row]
return cell1
}
else if indexPath.section == 1 {
let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCellTwo", for: indexPath) as! CollectionViewCell

cell2.cellTwoLabel.text = labelArray[indexPath.row]
return cell2
} else if indexPath.section == 2 {
let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCellOne", for: indexPath) as! CollectionViewCell
cell1.cellOneImage.image = imageArray[indexPath.row]
cell1.cellOneLabel.text = labelArray[indexPath.row]
return cell1
} else {
let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCellTwo", for: indexPath) as! CollectionViewCell
cell2.cellTwoImage.image = imageArray[indexPath.row]
cell2.cellTwoLabel.text = labelArray[indexPath.row]
return cell2
}
}

}

这是customCell xib文件

如果你需要的是每偶数行使用Cell1,每奇数行使用Cell2,那么不要检查特定的行,当你除以2(模数(indexPath.item%2==0 时检查余数

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item % 2 == 0 {
let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCellOne", for: indexPath) as! CollectionViewCell
cell1.cellOneLabel.text = labelArray[indexPath.row]
return cell1
}
} else {
let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCellTwo", for: indexPath) as! CollectionViewCell
cell2.cellTwoLabel.text = labelArray[indexPath.row]
return cell1
}
}
}

最新更新